【发布时间】:2019-05-31 05:07:10
【问题描述】:
我使用 Angular 2 创建了一个网站,并使用 node.js 作为后端。
我设法从 Angular 客户端向 node.js 服务器发送请求,并通过 HTTP 请求将其从 node.js 转发到另一个应用程序。我现在的目标是将第三个应用程序的响应发送回角度客户端页面(我也设法从第三个应用程序获取响应),但我是节点 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 方法到角度客户端(另请参阅第一条评论在代码中)?
非常感谢和
亲切的问候, 亚瑟敏
【问题讨论】:
-
这对我来说似乎是一个很常见的模式。也许这已经在这里得到了回答? stackoverflow.com/questions/39301227/…
-
我是否必须将管道放在 http.request 后面,因为这不起作用?
标签: javascript node.js express