简体   繁体   English

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

[英]ExpressJS : How to redirect a POST request with parameters

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. 重定向有效,但没有POST参数。 What should I modify to keep the POST parameters? 我应该修改什么来保留POST参数?

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. 307临时重定向(自HTTP / 1.1起)在这种情况下,请求应该使用另一个URI重复,但将来的请求仍然可以使用原始URI。 In contrast to 303, the request method should not be changed when reissuing the original request. 与303相反,在重新发出原始请求时不应更改请求方法。 For instance, a POST request must be repeated using another POST request. 例如,必须使用另一个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. 如果这不起作用,您还可以代表用户从服务器向另一台服务器发出POST请求。 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. 您将基本上代理请求。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM