簡體   English   中英

NodeJS/ExpressJS - 將 http 請求的響應發送回客戶端

[英]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 客戶端(另請參閱代碼中的第一條注釋) ?

非常感謝和

親切的問候,亞瑟明

編輯:似乎已經回答了這種類似的模式 - 外部 API 調用與 Express、Node.JS 和 Require 模塊感謝@madflow 找到它。

首先,我認為您正在做一些額外的工作,為什么不使用像 express.js 這樣的框架?

無論如何 - 我要做的是從/api/arq端點內向您的第三方發送請求,在收到路由內和res.on("end"...傳遞答案后調用http.request沿着。

 console.log('Response end: ' + responseString);

上一行是您擁有要在響應中發送的數據的位置。

所以在那里發送響應,而不是在你調用postCode之后立即postCode

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM