node.js: route request to different port on same host

前端 未结 3 1880
孤街浪徒
孤街浪徒 2021-01-17 23:07

I have a host computer which serves a number of webapplications (not node.js based). It does this using different ports. This means that for example the following applicatio

3条回答
  •  爱一瞬间的悲伤
    2021-01-18 00:01

    There is a nice http-proxy lib designed exactly for that!

    const httpProxy = require('http-proxy');
    const url = require('url');
    
    const proxy = httpProxy.createProxy();
    const options = {
        '/app/app1': 'http://localhost:3000',
        '/app/app2': 'http://localhost:3001',
        '/app/app3': 'http://localhost:3003',
    }
    
    require('http').createServer((req, res) => {
        const pathname = url.parse(req.url).pathname;
        for (const [pattern, target] of Object.entries(options)) {
            if (pathname === pattern || 
                pathname.startsWith(pattern + '/')
            ) {
                proxy.web(req, res, {target});
            }
        }
    }).listen(80);
    

提交回复
热议问题