0

so I'm pulling in data in express through an external api then outputting it on my page, however, when you navigate to /id it doesn't display the data till after you refresh the page. Any idea on how to fix or why it is causing it to do this?

//gets basic account datas
router.get('/:id', function(req, res, next) {
 request('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/'+ req.params.id +'?api_key=RGAPI-05a90f72-a07b-4d8f-bcb3-0a8f938d84ab', { json: true }, (err, res, body) => {
   data = body; 
   data =JSON.stringify(data);
   userString = body.id;
   console.log(userString);

 });
   res.send(data);
   res.redirect("/"+req.params.id);
});
yer
  • 19
  • 4
  • Looks like you are sending the server response **before** waiting for the request to your API to finish. You should move `res.send(data)` within the request callback. – Ramiz Wachtler Dec 03 '19 at 21:26

2 Answers2

0

Looks like you are sending the server response before waiting for the request to your API to finish. You should move res.send(data) within the request callback. Furthermore, I'd advice using environment variables to store your API key in, instead of exposing it for public view.

//gets basic account datas
router.get('/:id', function(req, res, next) {
 // I renamed "res" from request to "apiRes", otherwise you'll get an exception, because the "res.send(...)" would take the "res" from request
 request('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/'+ req.params.id +'?api_key=RGAPI-05a90f72-a07b-4d8f-bcb3-0a8f938d84ab', { json: true }, (err, apiRes, body) => {
   // data = body;  Not sure where you initiate this "data" variable
   // data =JSON.stringify(data);
   userString = body.id;
   console.log(userString);
   res.send(JSON.stringify(body));
 });
});
Ramiz Wachtler
  • 5,623
  • 2
  • 28
  • 33
0

As Ramiz Wachtler said in his comment you should send the response inside the callback of the request.

The key concept here is that the callback is going to be called when the request is ready to be processed, so after that you can process it and respond.

//gets basic account datas
router.get('/:id', function(req, res, next) {
 request('https://na1.api.riotgames.com/lol/summoner/v4/summoners/by-name/'+ req.params.id +'?api_key=RGAPI-05a90f72-a07b-4d8f-bcb3-0a8f938d84ab', { json: true }, (err, res, body) => {
   data = body; 
   data =JSON.stringify(data);
   userString = body.id;
   console.log(userString);

   res.send(data);
   res.redirect("/"+req.params.id);
 });
});
BlueKraken
  • 21
  • 3