ExpressJS : How to redirect a POST request with parameters

后端 未结 1 1466
迷失自我
迷失自我 2020-11-27 16:30

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)         


        
相关标签:
1条回答
  • 2020-11-27 17:15

    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
    
    0 讨论(0)
提交回复
热议问题