Proxy with express.js

前端 未结 9 1513
别那么骄傲
别那么骄傲 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:02

    Ok, here's a ready-to-copy-paste answer using the require('request') npm module and an environment variable *instead of an hardcoded proxy):

    coffeescript

    app.use (req, res, next) ->                                                 
      r = false
      method = req.method.toLowerCase().replace(/delete/, 'del')
      switch method
        when 'get', 'post', 'del', 'put'
          r = request[method](
            uri: process.env.PROXY_URL + req.url
            json: req.body)
        else
          return res.send('invalid method')
      req.pipe(r).pipe res
    

    javascript:

    app.use(function(req, res, next) {
      var method, r;
      method = req.method.toLowerCase().replace(/delete/,"del");
      switch (method) {
        case "get":
        case "post":
        case "del":
        case "put":
          r = request[method]({
            uri: process.env.PROXY_URL + req.url,
            json: req.body
          });
          break;
        default:
          return res.send("invalid method");
      }
      return req.pipe(r).pipe(res);
    });
    

提交回复
热议问题