Proxy with express.js

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

    I used the following setup to direct everything on /rest to my backend server (on port 8080), and all other requests to the frontend server (a webpack server on port 3001). It supports all HTTP-methods, doesn't lose any request meta-info and supports websockets (which I need for hot reloading)

    var express  = require('express');
    var app      = express();
    var httpProxy = require('http-proxy');
    var apiProxy = httpProxy.createProxyServer();
    var backend = 'http://localhost:8080',
        frontend = 'http://localhost:3001';
    
    app.all("/rest/*", function(req, res) {
      apiProxy.web(req, res, {target: backend});
    });
    
    app.all("/*", function(req, res) {
        apiProxy.web(req, res, {target: frontend});
    });
    
    var server = require('http').createServer(app);
    server.on('upgrade', function (req, socket, head) {
      apiProxy.ws(req, socket, head, {target: frontend});
    });
    server.listen(3000);
    

提交回复
热议问题