你能发送来自另一台服务器的HTTP响应吗?

也许愚蠢的问题。

最近我一直在玩Node.js,就像设置服务器和发出请求是多么容易。我还没有尝试过,但想知道如何将数据从一个请求转发到另一个服务器,并且第二台服务器向客户端发送响应。

这可能吗?

CLIENTX – > SERVER A – > SERVER B – > CLIENT X

最令我困惑的是如何发送给同一个客户端? 这个信息应该出现在请求头部,虽然不是? 是否将这些信息转发给SERVER B?

我处于一种情况,我正在接受Node.js服务器上的请求,并希望将一些数据转发给我创build的Laravel API,并将响应发送给客户端表单。

欣赏你的答案,

马特

这对于request模块来说很简单。

以下是“服务器A”的一个示例实现,它会将所有请求按原样传递给服务器B,并将其响应发送回客户端:

 'use strict'; const http = require('http'); const request = require('request').defaults({ followRedirect : false, encoding : null }); http.createServer((req, res) => { let endpoint = 'http://server-b.example.com' + req.url; req.pipe(request(endpoint)).pipe(res); }).listen(3000); 

而不是request你也可以用http模块实现这个,但是request使得它更容易。

任何对http://server-a.example.com/some/path/here请求将被传递给服务器B,具有相同的path(+方法,查询string,正文数据等)。

followRedirectencoding是两个选项,我发现有用的时候传递请求到这样的其他服务器。 他们在这里logging 。

正如已经提到的那样,它不是那样工作的。 服务器B不能将响应发送回客户端X ,因为这将作为对“无请求”的响应。 客户端X从不向服务器B询问任何事情。

米姆

这是如何工作的:

  1. 客户端X服务器A发出请求
  2. 在该请求的上下文中, 服务器A服务器B (您的Laravel API)发出请求,
  3. 服务器A记下从服务器B收到的响应
  4. 服务器A然后将响应发送回客户端X.

示例实现:

 var http = require('http'); function onRequest(request, response) { var options = { host: 'stackoverflow.com', port: 80, path: '/' }; var body = ''; http.get(options, function(responseFromRemoteApi) { responseFromRemoteApi.on('data', function(chunk) { // When this event fires we append chunks of // response to a variable body += chunk; }); responseFromRemoteApi.on('end', function() { // We have the complete response from Server B (stackoverflow.com) // Send that as response to client response.writeHead(200, { 'Content-type': 'text/html' }); response.write(body); response.end(); }); }).on('error', function(e) { console.log('Error when calling remote API: ' + e.message); }); } http.createServer(onRequest).listen(process.env.PORT || 3000); console.log('Listening for requests on port ' + (process.env.PORT || 3000));