Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
607 views
in Technique[技术] by (71.8m points)

node.js - 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.

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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.

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.

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...