[英]How to get response body from a http.request as a ctx.body for koa?
I'm learning Node.js, and for some reason I need to set up a http.request to another ip, and get the response from it and apply to ctx.body of koa. 我正在学习Node.js,出于某种原因,我需要为另一个IP建立一个http.request,并从中获取响应并将其应用于koa的ctx.body。 I wrote the code like this: 我写了这样的代码:
var refreshData = async (ctx, next) =>{
var option = {
host: 'xxx.xxx.xxx.xxx',
port: 8080,
path: '/reqPath',
method: 'POST',
headers:{'Content-Type': 'application/json'}
};
var postData = "1";
var resData = '';
var req = http.request(option, function(res){
res.setEncoding('utf8');
res.on('data', function (chunk) {
resData = resData + 'Chunk: ' + chunk;
});
res.on('end', function(){
ctx.res.body = resData;
console.log('ResponseData: ' + ctx.res.body); //shows the correct data
});
});
req.on('error', function(e){
console.log('problem with request: ' + e.message);
});
req.write(postData);
req.end();
};
module.exports = {
'GET /refreshDataGet': refreshData,
};
Learning to use controller mapping and it works, and resData is the correct data. 学习使用控制器映射,它可以工作,并且resData是正确的数据。 But I can only get 'status 0' when doing the 'GET /refreshDataGet' from the webpage. 但是从网页上执行“ GET / refreshDataGet”时,我只能获得“状态0”。 If I don't do the http.request and directly apply a JSON object to ctx.body, I can get the correct status and data on the webpage. 如果我不执行http.request并将JSON对象直接应用于ctx.body,则可以在网页上获取正确的状态和数据。 Did I miss something? 我错过了什么? Or there is a better solution to act this? 还是有更好的解决方案来执行此操作?
Thanks!! 谢谢!!
Edit: return 404, if manually set to 200 then find nothing in the response body. 编辑:返回404,如果手动设置为200,则在响应正文中找不到任何内容。 But the debug print is correct inside 但是里面的调试打印是正确的
res.on('end', function(){}) res.on('end',function(){})
The problem here is the following: within your async
function, you are defining a callback function. 这里的问题如下:在async
函数中,您正在定义一个回调函数。 This will lead to your 404, because the ascny / await pattern requires promises ... So what you basically have to do is to wrap your http.request
into another funttion which returns a promise. 这将导致您的404,因为ascny / await模式需要promise ...因此,您基本上要做的就是将http.request
包装到另一个返回promise的函数中。 So something like: 所以像这样:
// not tested !!
function getHttpRequest() {
let option = {
host: 'xxx.xxx.xxx.xxx',
port: 8080,
path: '/reqPath',
method: 'POST',
headers:{'Content-Type': 'application/json'}
};
return new Promise((resolve, reject) => {
let postData = "1";
let resData = '';
let req = http.request(option, function(res){
res.setEncoding('utf8');
res.on('data', function (chunk) {
resData = resData + 'Chunk: ' + chunk;
});
res.on('end', function(){
resolve(resData)
});
});
})
}
Then in your refreshData
async function you are awaiting the resolving promise like: 然后在您的refreshData
异步函数中,您正在等待以下解决承诺:
ctx.body = await getHttpRequest():
Hope that helps ... 希望有帮助...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.