Hello, I’m using node and express with node-fetch so I can call an api on the server to hide the api key. I’m wondering someone could explain now how to get the data with client side js after the server fetch’s the api?
Now I’m getting the data logged in the console as json, but I’m not sure how to access it via client side js.
//Require express framework
const express = require('express')
const fetch = require('node-fetch')
//Set express to app variable
const app = express()
const port = 3000
//Listen on port 3000 for server
app.listen(port, () => { console.log('listening at 3000') })
//Tell app which folder to use to show static on local server
app.use(express.static('public'))
const key = `65456464564564` //not real key
const api_url = `https://api.darksky.net/forecast/${key}/37.8267,-122.4233`
fetch(api_url,)
.then(res => res.json())
.then(json => console.log(json));
You need to create a micro service, preferably with some kind of authentication. The flow would be like this.
Your app makes a fetch call to your microservice.
Your microservice makes the call for the data.
Once it gets it, your microservice returns that data to your app.
I wrote something very similar for this silly little app. The code is in this repo.
I’m having a problem with this as well. I’m fetching data from an api in my backend app.js, the data I get from that has to then be used in a leaflet.js clientside file. I’ve tried using require but the moment I do that it won’t show anything on my page anymore. So I’m not sure how I would have to send that data through to my file
One possible approach would be callbacks or promises on both sides. The fetch on your backend is already a promise. Have you tried something with libraries like axios.js on your client?
That worked, thanks! However, that makes it so the page is essentially just a json file. How would I go about accessing it from a page so I can just input the data where it’s needed on the existing page? If that makes sense.