node 搭载本地代理,处理web本地开发跨域问题

var path = require('path')
var httpProxy = require('http-proxy')
var express = require('express')
var app = express()

var rootPath = path.join(__dirname, './');

var port = 8060;  // 指定服务端口
var filterFields = ['/api'];  // 过滤请求路径关键字 type: array

var proxy = httpProxy.createProxyServer({
    // target: 'http://sit.behuntergatherer.com/',   //代理 接口地址
    target: 'http://uat.behuntergatherer.com/',   //代理 接口地址
    // target: 'http://10.36.9.161:8080'
    // target: 'http://10.36.8.36:8083',
    changeOrigin: true,
    // 下面的设置用于https
    // ssl: {
    //     key: fs.readFileSync('server_decrypt.key', 'utf8'),
    //     cert: fs.readFileSync('server.crt', 'utf8')
    // },
    // secure: false
});

proxy.on('error', function(err, req, res){
    res.writeHead(500, {
        'content-type': 'text/plain'
    });
    console.log(err);
    res.end('Something went wrong. And we are reporting a custom error message.');
});

// 处理静态资源
app.use(express.static(rootPath));

// 只对 filterFields 数组元素有的字段请求,挂载此中间件
filterFields.forEach(function (field) {
    app.use(field, function (req, res, next) {
        var pathname = req.url;
        req.url = field + pathname;
        proxy.web(req, res);
    })
});

app.listen(port);

console.log("Server runing at : localhost:" + port + "/example/example.html");
原文地址:https://www.cnblogs.com/gavin007/p/8021900.html