Proxy with express.js

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

    I don't have have an express sample, but one with plain http-proxy package. A very strip down version of the proxy I used for my blog.

    In short, all nodejs http proxy packages work at the http protocol level, not tcp(socket) level. This is also true for express and all express middleware. None of them can do transparent proxy, nor NAT, which means keeping incoming traffic source IP in the packet sent to backend web server.

    However, web server can pickup original IP from http x-forwarded headers and add it into the log.

    The xfwd: true in proxyOption enable x-forward header feature for http-proxy.

    const url = require('url');
    const proxy = require('http-proxy');
    
    proxyConfig = {
        httpPort: 8888,
        proxyOptions: {
            target: {
                host: 'example.com',
                port: 80
            },
            xfwd: true // <--- This is what you are looking for.
        }
    };
    
    function startProxy() {
    
        proxy
            .createServer(proxyConfig.proxyOptions)
            .listen(proxyConfig.httpPort, '0.0.0.0');
    
    }
    
    startProxy();
    

    Reference for X-Forwarded Header: https://en.wikipedia.org/wiki/X-Forwarded-For

    Full version of my proxy: https://github.com/J-Siu/ghost-https-nodejs-proxy

提交回复
热议问题