如何修复我的代码,使其发送 json 数据作为对邮递员 GET 请求的响应?

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

我通过代码接收的数据通过 console.log 输出到 cmd,但我似乎无法弄清楚如何使相同的数据可用于邮递员的 GET 请求。谢谢

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

您在 request.get 的回调中使用了 res.send。但是在这种情况下,res 是来自您调用的 API 的 incoming 响应,而不是创建的 outgoing 响应通过你的应用程序。只有 传出 响应包含 send 方法。

要将两者分开,请使用不同的名称:

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

res.send 是 express 的一部分。如果失败的 res.send 在 request.get 中,那是因为它不是 express.

的一部分

request 的文档中说响应参数将是 http.IncomingMessage 的一个实例。那应该意味着您可以简单地使用 res.end

编辑:

@HeikoTheißen 是对的。没有res.end.

但这可以用不同的方式处理。如果我们可以将 get 请求包装在一个 promise 中,那么我们就可以使用 get 请求需要发送的任何内容来解决这个 promise。

一个例子:

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!'}

你只需像这样将其通过管道传递给响应 .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}`);
});