Retrieving API data from node

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));

Thanks!

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.

Thanks! I’ll check it out.

Do you know where I can find an example or what docs I should look at? I’m having a hard time understanding from Kevin’s project.

Thanks, I’ll go through the lessons to make sure I understand.

Hi Trey,

You can have the fetch() as part of an app.get callback function and send the response data from fetch as part of the response. Something like this:

app.get("/darksky", (req, res) => {
fetch....
.then(res => res.json())
.then(json =>res.send({json}))

})

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

Hi @olib114,

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.

Hi Trey,

In that case, you can send something like this as the response:

.then(json =>res.send(
   `<html>
       <head>...</head>
       <body><h1>This is the data ${json.data}</h1></body>
    </html>`
))

Or use a framework, like React to send pages that take props and pass the json data in as props.