Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 258
MartinMoizard Avatar asked Jul 12 '13 10:07

MartinMoizard


People also ask

How do I redirect POST Express?

The res. redirect() function lets you redirect the user to a different URL by sending an HTTP response with status 302. The HTTP client (browser, Axios, etc.) will then "follow" the redirect and send an HTTP request to the new URL as shown below.

What is POST () in Express?

js POST Method. Post method facilitates you to send large amount of data because data is send in the body. Post method is secure because data is not visible in URL bar but it is not used as popularly as GET method. On the other hand GET method is more efficient and used more than POST.

How do I use req parameters in node JS?

The req. params property is an object containing properties mapped to the named route “parameters”. For example, if you have the route /student/:id, then the “id” property is available as req.params.id. This object defaults to {}.


1 Answers

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 
like image 96
mak Avatar answered Sep 24 '22 17:09

mak