0

Trying to keep my code organized. I have a controller directory and router directory. The goal is to make an api call and retrieve data.

CONTROLLER

function searchName(req, res) {
res.setHeader("user-key", process.env.APIKEY)
res.redirect(`https://api-endpoint.igdb.com/games/?search=${req.params.game}&fields=*`)

 }

ROUTER

router.get('/search/:game', Controller.searchName)

I export router, and require it in my server.js file. In POSTMAN, this works fine; I do have my API Key hard coded in Postman. I've tried many different methods but can't seem to pass the header with my ApiKey when making the initial request in the code. Additionally, being new to nodejs, I'm not sure if the request redirect is sufficient in this scenario. Ultimately, setHeader is not working

Chris Simmons
  • 249
  • 2
  • 7
  • 19
  • Have you seen this? https://stackoverflow.com/questions/39997413/how-to-pass-headers-while-doing-res-redirect-in-express-js – Anand Undavia Sep 03 '18 at 09:39
  • Thank you for reply! I just read through it. It seems a redirect isn’t what I want to do at all. I don’t want to redirect to another page, I simply want to make api call and retrieve data. Hmm – Chris Simmons Sep 03 '18 at 09:42
  • Yeah! you might want to use `isomorphic-fetch` for that. https://www.npmjs.com/package/isomorphic-fetch – Anand Undavia Sep 03 '18 at 09:44

1 Answers1

0

It sounds like you're trying to make an async call to another service, pull back some data, and send that back to the client that called your service. In a nodejs application it's quite trivial to make a new HTTP request. Nodejs has a built in HTTP.Agent, but I'd suggest trying out the axios library as it makes it even easily. This will result in something like this:

const axios = require('axios');

function searchGame(req, res) {
    const requestOptions = {
        method: 'GET',
        uri: `https://api-endpoint.igdb.com/games/?search=${req.params.game}&fields=*`,
        headers: {
            "user-key": process.env.API_KEY
        }
    }

    axios.get(requestOptions)
    .then(function (response) {
        // This is the data the remote service gave back
        res.send(response.data);
    })
    .catch(function (error) {
        // The remote gave an error, lets just forward that for now
        res.send({error: error});
    });
}

Here we build an axios request from the req object, we make the request using axios.get, we then wait for the "promise" (this is an async javascript concept if you've not come across it before), then we take the response from that and forward it back as the res. Lets pretend for argument sake that this is a JSON response, but it could be anything.

Elliot Blackburn
  • 3,759
  • 1
  • 23
  • 42