app.post('/getDetails', async function (req, res) {
var body
var post_req = await https.request(post_options, function (res) {
res.setEncoding('utf8');
body = '';
res.on('data', function (chunk) {
body += chunk;
console.log(body);
console.log(JSON.parse(body));
newBody = body;
}).on('error', function (error) {
console.log(error)
});
});
post_req.write(requestBody);
post_req.end();
res.send(body);
});
res.send(body)发送未定义,我在res.send(body)之前放置了console.log(body),它显示未定义,并且在变量post_req内,body具有值
答案 0 :(得分:0)
正如我在评论中提到的那样,您正在尝试将Async-Await与回调一起使用。您不能将Async-Await语法与回调一起使用。与诺言一起使用Async / Await。
您必须为回调编写promise包装器,或者可以使用请求-承诺模块返回promise。
承诺包装:
app.post('/getDetails', async function (req, res) {
var body
function httpReq(post_options){
return new Promise(function(resolve, reject){
https.request(post_options, function (res) {
res.setEncoding('utf8');
body = '';
res.on('data', function (chunk) {
body += chunk;
console.log(body);
console.log(JSON.parse(body));
newBody = body;
resolve();
}).on('error', function (error) {
console.log(error)
reject()
});
});
})
}
var post_req = await httpReq(post_options)
...
...
res.send(body);
});