JoeIsBlogging
JoeIsBlogging

Reputation: 185

Pass response data from one http request into the next

I'm trying to make a request, and using the data I receive pass that on to another request appending that data to the URL.

I've tried to create a function underneath the route and then call that function inside of the route, but that didn't work..

const express = require('express');
const router = express.Router();
const fetch = require('node-fetch');

let accId;

router.get('/:platform/:name', async (req, res) => {
    try {
        const headers = {
            'X-Riot-Token': process.env.TRACKER_API_KEY
        }

        const { platform, name } = req.params;

        const response = await fetch(`https://euw1.api.riotgames.com/lol/summoner/v4/summoners/by-name/${name}`, {
            headers
        });

        const data = await response.json();

        if(data.errors && data.errors.length > 0) {
            return res.status(404).json({
                message: 'No summoner found'
            })
        }
        res.json(data);
        accId = data.accountId;

    } catch (error) {
        console.error(error);
        res.status(500).json({
            message: 'Server Error'
        })
    }
});

module.exports = router;

Where you see the variable accId I want to add that to a URL and then make another request. Any pointers would be great, thanks..

Upvotes: 0

Views: 1888

Answers (2)

shubham verma
shubham verma

Reputation: 53

You can solve this problem by using superagent. You can use either async await or using promises.

const sa = require('superagent');

router.get('/:platform/:name', async (req, res) => {
    const url = 'YOUR_URL_ONE';
    const anotherUrl = 'YOUR_URL_Two';

    //Promisified request object
    const reqOne = sa.get(url).set('X-Riot-Token', 'process.env.TRACKER_API_KEY');   

    return reqOne.then((data) => { 
     // do whatever you want with data then call another url, you can change the mothod to post or put as well
        const reqTwo = sa.post(anotherUrl).set('X-Riot-Token', 'process.env.TRACKER_API_KEY').send(data);; 
      return reqTwo;
    }).then((data)=>{
    return res.json(data);
    }).catch(()=>{
       // handle expection
    });
});

module.exports = router;

Upvotes: 0

Kaan Sentürk
Kaan Sentürk

Reputation: 36

You cannot send a second request, since you previously send a response with res.json(data).

I would solve this by passing the data to another endpoint. Add your data to req.locals

req.locals.data = data;

And then redirect to another endpoint of yours, where you handle your second request with:

res.redirect(/other/endpoint);

In your other endpoint you can then send both results together after handled the accountId case.

app.get(/other/endpoint, (req, res) => {
  res.send({ data: req.locals.data, accIdResult: doSomething(req.locals.data. accountId)});
});

Upvotes: 1

Related Questions