【问题标题】:NodeJS/ExpressJS - Send response of http request back to clientNodeJS/ExpressJS - 将 http 请求的响应发送回客户端
【发布时间】: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


【解决方案1】:

编辑:似乎已经回答了这种类似的模式 - External API Calls With Express, Node.JS and Require Module 感谢@madflow 找到它。

在我看来,首先你做了一些额外的工作,为什么不使用 express.js 之类的框架?

无论如何 - 我要做的是从 /api/arq 端点内向您的第三方发送请求,在路由内收到请求后调用 http.request 并在 res.on("end"... 内传递答案。

【讨论】:

  • 我想,我已经在使用 expressjs 了?如何在 res.on("end") 中传递答案?我已经在这个地方尝试过 res.send,但没有成功。
  • 如前所述,这是行不通的。我收到错误消息“未解析的函数或方法状态()”
  • 谢谢 JBK。这就是解决方案。
  • @Yasemin K. 很乐意提供帮助,如果您将我的答案标记为正确答案将不胜感激???
  • ...干得好,不放弃,几天后实际解决它! ??
【解决方案2】:
  console.log('Response end: ' + responseString);

以上行是您要在响应中发送的数据的位置。

所以发送响应那里,而不是在您致电postCode 之后立即发送。

【讨论】:

    猜你喜欢
    • 2018-10-12
    • 1970-01-01
    • 2015-04-26
    • 1970-01-01
    • 2014-09-13
    • 1970-01-01
    • 2019-07-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多