node.js ExpressJS:如何使用参数重定向 POST 请求

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17612695/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 15:01:22  来源:igfitidea点击:

ExpressJS : How to redirect a POST request with parameters

node.jsexpress

提问by MartinMoizard

I need to redirect all the POST requests of my node.js server to a remote server.

我需要将 node.js 服务器的所有 POST 请求重定向到远程服务器。

I tried doing the following:

我尝试执行以下操作:

app.post('^*$', function(req, res) {
  res.redirect('http://remoteserver.com' + req.path);
});

The redirection works but without the POST parameters. What should I modify to keep the POST parameters?

重定向有效,但没有 POST 参数。我应该修改什么来保留 POST 参数?

回答by mak

In HTTP 1.1, there is a status code (307) which indicates that the request should be repeated using the same method and post data.

在 HTTP 1.1 中,有一个状态代码 (307),它指示应该使用相同的方法和发布数据重复请求。

307 Temporary Redirect (since HTTP/1.1) In this occasion, the request should be repeated with another URI, but future requests can still use the original URI. In contrast to 303, the request method should not be changed when reissuing the original request. For instance, a POST request must be repeated using another POST request.

307 Temporary Redirect(自 HTTP/1.1 起) 在这种情况下,应该使用另一个 URI 重复请求,但未来的请求仍然可以使用原始 URI。与303相反,重新发出原始请求时不应更改请求方法。例如,必须使用另一个 POST 请求重复 POST 请求。

In express.js, the status code is the first parameter:

在 express.js 中,状态码是第一个参数:

res.redirect(307, 'http://remoteserver.com' + req.path);

Read more about it on the programmers stackexchange.

程序员 stackexchange上阅读更多关于它的信息。

Proxying

代理

If that doesn't work, you can also make POST requests on behalf of the user from the server to another server. But note that that it will be your server that will be making the requests, not the user. You will be in essence proxying the request.

如果这不起作用,您还可以代表用户从服务器向另一台服务器发出 POST 请求。但请注意,发出请求的是您的服务器,而不是用户。您实际上将代理请求。

var request = require('request'); // npm install request

app.post('^*$', function(req, res) {
    request({ url: 'http://remoteserver.com' + req.path, headers: req.headers, body: req.body }, function(err, remoteResponse, remoteBody) {
        if (err) { return res.status(500).end('Error'); }
        res.writeHead(...); // copy all headers from remoteResponse
        res.end(remoteBody);
    });
});

Normal redirect:

正常重定向:

user -> server: GET /
server -> user: Location: http://remote/
user -> remote: GET /
remote -> user: 200 OK

Post "redirect":

发布“重定向”:

user -> server: POST /
server -> remote: POST /
remote -> server: 200 OK
server -> user: 200 OK