How can I fix my code to make it send the json data as a response to postman's GET requests?

Viewed 186

The data I am receiving through the code is outputting to the cmd through console.log but I can't seem to figure out how to make that same data available for GET requests from postman. Thank you

    const express = require('express');
const app = express();
const PORT = 5000;
const apicall = require('./apicall');
const request = require('request');

app.get('/', (req, res) => {
    res.send("Hello world!")
    
});
   
app.get('/getinfo', (req, res, body) => {
    const getToken = (url, callback) => {
        const options = {
            url: process.env.GET_TOKEN,
            json: true,
            body: {
                client_id: process.env.CLIENT_ID,
                client_secret: process.env.CLIENT_SECRET,
                grant_type: 'client_credentials'
            }
        };
    
        request.post(options, (err, res, body) => {
            if(err) {
                return console.log(err)
            }
            console.log(`Status: ${res.statusCode}`)
            console.log(body);
    
            callback(res);
        });
    }
    
    var AT = '';
    var info = '';
    getToken(process.env.GET_TOKEN, (res) => {
        AT = res.body.access_token;
        return AT;
    });
    
    const getGames = (url, accessToken, callback) => {
        const gameOptions = {
            url: process.env.GET_GAMES,
            method: 'GET',
            headers: {
                'Client-ID': process.env.CLIENT_ID,
                'Authorization': 'Bearer ' + accessToken
            }
        };
    
        request.get(gameOptions, (err, res, body) => {
            if(err) {
                return console.log(err);
            }
            let x = '';
            console.log(`Status: ${res.statusCode}`);
            console.log(JSON.parse(body));
            //res.send(parsed);
            //req.body.getinfo = JSON.parse(body);
        })
    }
    
    setTimeout(() => {
       getGames(process.env.GET_GAMES, AT, (response) => {
    
        });
    }, 1000);
    //res.send(JSON.parse(body));
});

app.listen(PORT, () => {
    console.log(`Example app listening on port ${PORT}`);
});
3 Answers

You use res.send in the callback of a request.get. But in that context, res is the incoming response from the API that you call, not the outgoing response created by your app. Only the outgoing response contains a send method.

To keep both separate, use different names:

app.get("/getinfo", function(req, res) {
  request.get(..., function(err, incoming_res, body) {
    res.json(JSON.parse(body));
  });
});

res.send is a part of express. If the res.send that's failing is in request.get then that's because it's not a part of express.

From the docs for request it says that the response argument will be an instance of http.IncomingMessage. That should mean you can simply use res.end

Edit:

@HeikoTheißen is right. There is no res.end.

But this could be handled in a different way. If we can wrap the get request inside a promise, then we could resolve the promise with whatever needs to be sent from the get request.

An example:

const result = await new Promise((resolve) => {
    request(gameOptions, function (error, response, body) {
         resolve ({status : 'A Ok!'}) // <--- send response here
    }
}
console.log ("result is ", result) // <-- Object {status : 'A Ok!'}

You just pipe it to the response like so .pipe(res)

const express = require('express');
const app = express();
const PORT = 5000;
const apicall = require('./apicall');
const request = require('request');

app.get('/', (req, res) => {
    res.send("Hello world!")
    
});

app.get('/ne2', (req, res) => {
    //res.send('This is the new endpoint');
    apicall.getCall;
});
   
app.get('/getinfo', (req, res, body) => {
    const getToken = (url, callback) => {
        const options = {
            url: process.env.GET_TOKEN,
            json: true,
            body: {
                client_id: process.env.CLIENT_ID,
                client_secret: process.env.CLIENT_SECRET,
                grant_type: 'client_credentials'
            }
        };
    
        request.post(options, (err, res, body) => {
            if(err) {
                return console.log(err)
            }
            console.log(`Status: ${res.statusCode}`)
            console.log(body);
    
            callback(res);
        });
    }
    
    var AT = '';
    var info = '';
    getToken(process.env.GET_TOKEN, (res) => {
        AT = res.body.access_token;
        return AT;
    });
    
    const getGames = (url, accessToken, callback) => {
        const gameOptions = {
            url: process.env.GET_GAMES,
            method: 'GET',
            headers: {
                'Client-ID': process.env.CLIENT_ID,
                'Authorization': 'Bearer ' + accessToken
            }
        };
    
        request.get(gameOptions, (err, res, body) => {
            if(err) {
                return console.log(err);
            }
            let x = '';
            console.log(`Status: ${res.statusCode}`);
            //console.log(JSON.parse(body));
            info = JSON.parse(body);
            console.log(info);
            //res.send(parsed);
            //req.body.getinfo = JSON.parse(body);
        }).pipe(res);
    }
    
    setTimeout(() => {
       getGames(process.env.GET_GAMES, AT, (response) => {
    
        });
    }, 1000);
    //res.send(info);
    
});

app.listen(PORT, () => {
    console.log(`Example app listening on port ${PORT}`);
});
Related