gpt4 book ai didi

node.js - ExpressJS : How to redirect a POST request with parameters

转载 作者:IT老高 更新时间:2023-10-28 22:02:50 26 4
gpt4 key购买 nike

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

我尝试了以下操作:

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

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

最佳答案

在 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.

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

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

programmers stackexchange 上了解更多信息.

代理

如果这不起作用,您还可以代表用户从服务器向另一台服务器发出 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);
});
});

正常重定向:

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

关于node.js - ExpressJS : How to redirect a POST request with parameters,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17612695/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com