[英]Send NodeJS ExpressJS Response HTTP Status code 200 + payload
[英]NodeJS/ExpressJS - Send response of http request back to client
我使用 Angular 2 创建了一个网站,我使用 node.js 作为后端。
我设法从 angular 客户端向 node.js 服务器发送请求,并通过 HTTP 请求将其从 node.js 转发到另一个应用程序。 我现在的目标是将来自第三个应用程序的响应发送回 angular 客户端页面(我也设法从第三个应用程序获取响应),但我是 node js/express 的新手,我无法获得从 HTTP 请求中提取响应正文并将其发送回 angular 客户端。
在 nodejs 服务器中,我有以下代码(主要是通过查看教程):
app.route('/api/test').post((req, res) => {
postCode(JSON.stringify(req.body));
//Here I want to send back the response from the third application
//to the Angular client (instead of 'Hi')
res.status(200).send('Hi');
});
function postCode(post_data) {
const post_options = {
host: '127.0.0.1',
port: '8080',
path: '/test',
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(post_data)
}
};
// Set up the request
const post_req = http.request(post_options, function (res) {
res.setEncoding('utf8');
let responseString = ''
res.on('data', function (data) {
responseString += data;
console.log('Response data: ' + responseString);
});
res.on("end", function (data) {
responseString += data;
console.log('Response end: ' + responseString);
});
});
// post the data
post_req.write(post_data);
post_req.end();
}
那么,我现在如何管理“使用”HTTP 请求的响应并将其在 app.route('/api/arq')?post 方法中发送回 angular 客户端(另请参阅代码中的第一条注释) ?
非常感谢和
亲切的问候,亚瑟明
首先,我认为您正在做一些额外的工作,为什么不使用像 express.js 这样的框架?
无论如何 - 我要做的是从/api/arq
端点内向您的第三方发送请求,在收到路由内和res.on("end"...
传递答案后调用http.request
沿着。
console.log('Response end: ' + responseString);
上一行是您拥有要在响应中发送的数据的位置。
所以在那里发送响应,而不是在你调用postCode
之后立即postCode
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.