【问题标题】:Can you send HTTP Response from another Server?您可以从另一台服务器发送 HTTP 响应吗?
【发布时间】:2017-01-20 01:55:29
【问题描述】:

也许是个愚蠢的问题。

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

这可能吗?

CLIENTX -> 服务器 A -> 服务器 B -> 客户端 X

让我困惑的是如何发送给同一个客户?此信息应该出现在请求标头中,但不是吗?是否需要将该信息转发给 SERVER B?

我正在接受 Node.js 服务器上的请求,并希望将一些数据转发到我创建的 Laravel API 并将响应发送到那里的客户端表单。

感谢您的回答,

马特

【问题讨论】:

  • HTTP 响应是,嗯,响应,它们只能作为对客户端请求的响应发送。客户端不会兑现来自服务器的完全不请自来的“响应”。您是否想象客户端 X 大致同时向服务器 A 和服务器 B 发送请求?或者客户端 X 会在很久以后向服务器 B 发送请求?
  • 或者让服务器 A 对服务器 B 进行 API 调用并将结果返回给客户端 X 是否可以? (即客户端 X 不需要知道服务器 B 的存在)

标签: node.js http laravel-5 server response


【解决方案1】:

如前所述,它不是那样工作的。 服务器 B 无法将响应发送回 客户端 X,因为这将作为对 NO REQUEST 的响应。 客户端 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));

【讨论】:

    【解决方案2】:

    使用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。

    followRedirectencoding 是我发现在向其他服务器传递请求时有用的两个选项。它们记录在here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-11
      • 1970-01-01
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多