Proxy with express.js

前端 未结 9 1451
别那么骄傲
别那么骄傲 2020-11-28 00:29

To avoid same-domain AJAX issues, I want my node.js web server to forward all requests from URL /api/BLABLA to another server, for example other_domain.co

相关标签:
9条回答
  • 2020-11-28 01:22

    I found a shorter solution that does exactly what I want https://github.com/http-party/node-http-proxy

    After installing http-proxy

    npm install http-proxy --save
    

    Use it like below in your server/index/app.js

    var proxyServer = require('http-route-proxy');
    app.use('/api/BLABLA/', proxyServer.connect({
      to: 'other_domain.com:3000/BLABLA',
      https: true,
      route: ['/']
    }));
    

    I really have spent days looking everywhere to avoid this issue, tried plenty of solutions and none of them worked but this one.

    Hope it is going to help someone else too :)

    0 讨论(0)
  • 2020-11-28 01:23

    I found a shorter and very straightforward solution which works seamlessly, and with authentication as well, using express-http-proxy:

    const url = require('url');
    const proxy = require('express-http-proxy');
    
    // New hostname+path as specified by question:
    const apiProxy = proxy('other_domain.com:3000/BLABLA', {
        proxyReqPathResolver: req => url.parse(req.baseUrl).path
    });
    

    And then simply:

    app.use('/api/*', apiProxy);
    

    Note: as mentioned by @MaxPRafferty, use req.originalUrl in place of baseUrl to preserve the querystring:

        forwardPath: req => url.parse(req.baseUrl).path
    

    Update: As mentioned by Andrew (thank you!), there's a ready-made solution using the same principle:

    npm i --save http-proxy-middleware
    

    And then:

    const proxy = require('http-proxy-middleware')
    var apiProxy = proxy('/api', {target: 'http://www.example.org/api'});
    app.use(apiProxy)
    

    Documentation: http-proxy-middleware on Github

    I know I'm late to join this party, but I hope this helps someone.

    0 讨论(0)
  • 2020-11-28 01:29

    To extend trigoman's answer (full credits to him) to work with POST (could also make work with PUT etc):

    app.use('/api', function(req, res) {
      var url = 'YOUR_API_BASE_URL'+ req.url;
      var r = null;
      if(req.method === 'POST') {
         r = request.post({uri: url, json: req.body});
      } else {
         r = request(url);
      }
    
      req.pipe(r).pipe(res);
    });
    
    0 讨论(0)
提交回复
热议问题