简体   繁体   中英

How to redirect post request to other url in node.js?

I am trying to redirect a post request from one server to another server with additional parameters from request 1. You can check the below code.

app.use(bodyParser.urlencoded({ extended: true }));

app.post('/pay1',(req,res)=>{
    console.log(req._body);
    console.log(req.body); // output {'a':'value'}
    req.body['new']='other';
    console.log(req._body);
    console.log(req.body); // {'a':'value','new':"other"}
    res.redirect(307,'/pay2');
});

app.post('/pay2',(req,res)=>{
// this request will be in other server, for now I am testing in same server
    console.log(req.body); // output {'a':'value'}
    res.send('2dsaf');
});

How to pass extra fields to other request?

The 307 response says the request should be repeated to the new URL with the same method, but there is no way for you to change the request body the browser will send.

If you could use GET instead, you would be able to change the parameters (since they are part of the request path).

You could instead proxy the request, by sending it freshly to the new server from your server side, and pass the response back to your client. If you do things this way, you would be able to change the body however you like.

Another option would be to instead respond with an HTML page encoding the posted data in hidden form fields, plus the fields you wanted to add, and have the user click a submit button. You'd point the form's action at the other server.

I could do this to my code and all working just add new parameters and parse it there

app.use(bodyParser.urlencoded({ extended: true }));

app.post('/pay1',(req,res)=>{
    console.log(req._body);
    console.log(req.body); // output {'a':'value'}
    req.body['new']='other';
    console.log(req._body);
    console.log(req.body); // {'a':'value','new':"other"}
    res.redirect(307,'/pay2?a=value');
});

app.post('/pay2',(req,res)=>{
// this request will be in other server, for now I am testing in same server
    console.log(req.query.a + req.query.whatever //Whatever you have in the first request too); // output {'a':'value'}
    res.send('2dsaf');
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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