ExpressJS:如何使用参数重定向POST请求 [英] ExpressJS : How to redirect a POST request with parameters

查看:124
本文介绍了ExpressJS:如何使用参数重定向POST请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我尝试执行以下操作:

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

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

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

推荐答案

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

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.


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

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.

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

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

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

请阅读更多关于

Read more about it on the programmers stackexchange.

如果不起作用,您也可以代表用户将POST请求从服务器发送到另一个服务器。但请注意,这将是您的服务器将提出请求,而不是用户。您将在本质上代理请求。

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.

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

正常重定向:

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

发布重定向:

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

这篇关于ExpressJS:如何使用参数重定向POST请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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