您可以从其他服务器发送HTTP响应吗? [英] Can you send HTTP Response from another Server?

查看:52
本文介绍了您可以从其他服务器发送HTTP响应吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

傻问题.

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

I've been playing with Node.js lately, and like how easy it is to set up servers and make requests etc. I haven't tried yet, but was wondering how I might forward data from one request to another server, and have that second server send response to the client.

这可能吗?

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

CLIENTX -> SERVER A -> SERVER B -> CLIENT X

让我困惑的是如何发送给同一客户?该信息应该出现在请求标头中,尽管不是吗?将信息转发到服务器B只是一个问题?

Whats confusing to me is how to send to same client? This information should be present in the request header though no? Is it a matter of forwarding that information to SERVER B?

我处于一种在Node.js服务器上接受请求的情况下,想将一些数据转发到我创建的Laravel API并将响应发送到那里的客户端表单.

I am in a situation where I am accepting requests on a Node.js server, and would like to forward some of the data to a Laravel API I have created and send response to client form there.

欣赏您的答案,

马特

推荐答案

使用 请求 模块.

这是服务器A"的示例实现,它将所有请求原样传递到服务器B,然后将其响应发送回客户端:

Here's an example implementation for "Server A", that would pass all requests to Server B as-is, and send back its responses to the client:

'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);

您也可以使用 http 模块,但是 request 使其更容易.

Instead of request you could also implement this with the http module, but request makes it easier.

任何对 http://server-a.example.com/some/path/here 的请求将通过相同的路径(+方法,查询字符串,主体数据)传递给服务器B, 等等).

Any requests to http://server-a.example.com/some/path/here will be passed to Server B, with the same path (+ method, query strings, body data, etc).

followRedirect encoding 是两个有用的选项.在此处记录.

followRedirect and encoding are two options that I found useful when passing requests to other servers like this. They are documented here.

这篇关于您可以从其他服务器发送HTTP响应吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆