How to forward a request to other endpoint in node.js

后端 未结 3 1452
野的像风
野的像风 2020-12-09 05:22

In my scenario I need forward get request to another end point. In my machine there are two servers php and node.js server. Node.js is like a \"man in the middle\", PHP serv

相关标签:
3条回答
  • 2020-12-09 05:34

    In you case res.redirect might help.

    app.get('/track', function(req, res) {
       // process the request
    
       // then redirect
       res.redirect('/final-endpoint');
    });
    

    Then catch the redirected request in final endpont.

    app.get('/final-endpoint', function(req, res) {
           // proceess redirected request here.
    });
    

    See the Express docs

    0 讨论(0)
  • 2020-12-09 05:53

    Depending on what you're trying to do, you can create a new request to the end-point:

    //endpoint for tracking
    app.get('/track', function(req, res) {
    
      req.get({url: 'http://end-point', headers: req.headers});
    
      processRequest(req);
      res.setHeader('Content-Type', 'application/json');
      res.send('Req OK');
    });
    

    More info: https://github.com/request/request

    0 讨论(0)
  • 2020-12-09 05:54

    If your second endpoint is on a different server, (e.g. PHP) then you're going to need to either redirect the client (as in sohel's answer), or spoof a request from Node to the PHP server and then send the response back to the client. This latter option is definitely non-trivial so I would question whether it's crucial not to use a client redirect.

    If you're talking about two express endpoints, then I think the simplest answer might be not to actually forward at all, but just use the endpoint callback directly instead:

    app.get('/track', trackCallback);
    app.get('/otherendpoint', otherendpointCallback);
    
    function otherendpointCallback(req, res) {
      // do your thing
    }
    
    function trackCallback(req, res) {
    
      otherendpointCallback(req, res);
    
      processRequest(req);
      res.setHeader('Content-Type', 'application/json');
      res.send('Req OK');
    };
    

    Depending on exactly what you want to do at the other end point, you might need to spoof some of req's fields (e.g. req.url)

    0 讨论(0)
提交回复
热议问题