简单用node.js实现反向代理

废话不多说,

//index.js

const http = require('http'),
    express = require('express'),
    httpProxy = require('http-proxy'),
    proxy = httpProxy.createProxyServer({
        xfwd: true
    }),
    config = require('./config'),
    fs = require('fs'),
    path = require('path'),
    app = express()

app.use((req, res) => {
    config.forEach(o=> {
        if(req.headers.host == o.host){
            proxy.web(req, res, {
                target: 'http://' + o.proxy
            })
        }
    })
})

var cookie = ""
proxy.on('proxyReq', function (proxyReq, req, res) {
    req.headers.cookie = cookie + req.headers.cookie
    proxyReq._headers = req.headers
    return req
});

proxy.on('proxyRes', function (proxyRes, req, res) {
    var JSESSIONID = proxyRes.headers['set-cookie']
    if (JSESSIONID) {
        cookie = JSESSIONID;
        res.setHeader('Set-Cookie', proxyRes.headers['set-cookie'])
    }
});

proxy.on('error', function (proxyReq, req, res) {
    res.send("

404 Not Found

") }); console.log("服务已经启动!") app.listen(80)
// config.js

module.exports = [
    {
        host: 'www.test.com',
        proxy: '127.0.0.1:8001'
    },
    {
        host: 'pc.test.com',
        proxy: '127.0.0.1:8002'
    },
    {
        host: 'admin.test.com',
        proxy: '127.0.0.1:8800'
    },
]

你可能感兴趣的:(简单用node.js实现反向代理)