nodejs+express统一代理配置

var createError = require(‘http-errors’);
var express = require(‘express’);
var path = require(‘path’);
var cookieParser = require(‘cookie-parser’);
var logger = require(‘morgan’);
var history = require(‘connect-history-api-fallback’);
var ejs=require(‘ejs’);
//统一代理配置
var proxyxx= require(’./proxy/index’);
//原express自带测试用
var usersRouter = require(’./routes/users’);
//微信公众号
//var wechat = require(’./routes/wechat’);

var app = express();

//调整为ejs并调整模板为html格式
app.set(‘views’, path.join(__dirname, ‘views’));
//app.set(‘view engine’, ‘ejs’);
app.engine(‘html’, require(‘ejs’).renderFile);
app.set(‘view engine’, ‘html’);

app.use(logger(‘dev’));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
//必须放在app.use(express.static之前(解决vue下history模式404)
app.use(history({
verbose: true,
rewrites: [
//vue单页面,存在多个vue项目可配置多个如:to:‘app1’ to:‘app2’
{from: //k5003/.*KaTeX parse error: Expected 'EOF', got '}' at position 11: /, to: '/'}̲,// 尝试一 /…/,to: function(context) {return context.parsedUrl.path}}// 尝试二
]
//指定静态文件路径
app.use(express.static(path.join(__dirname, ‘public’)));
//配置代理服务规则例子
/*var options = {
target: ‘http://127.0.0.1:8088’, //转发到的地址
changeOrigin: true, //是否允许跨域
ws: true, // 代理websocket
pathRewrite: {
‘^/apis’: ‘’, // 重写路径
}
};
var exampleProxy = proxy(options);

app.use(’/apis’, exampleProxy);
*/
//接入代理模块
proxyxx.startTask(app);
//测试用例模块
app.use(’/users’, usersRouter);
//接入微信公众号模块
//app.use(’/wechat’, indexRouter);

// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get(‘env’) === ‘development’ ? err : {};

// render the error page
res.status(err.status || 500);
res.render(‘error’);
});

module.exports = app;

-----------/proxy/index
var proxy = require(‘http-proxy-middleware’);
var $conf = require(’…/conf/proxyurl’);
/**
*exports 代理
*/
module.exports = {
startTask:function(app){
let proxyList = $conf.datasur;
var config={};
for (let i = 0; i < proxyList.length; i++) {
const proxyElement = proxyList[i];
if(proxyElement.changeOrigin){
console.log([Proxy]: ${proxyElement.src} --> ${proxyElement.target});
let api=’^’+proxyElement.src;
config[api]=’’;
app.use(proxyElement.src,proxy({
target: proxyElement.target,
ws:true,
changeOrigin: true,
pathRewrite: config
}));
}
}
}
}
-------------------./conf/proxyurl
//路由配置
module.exports = {
datasur:[{
“src”: “/apis”,
“target”: “https://www.k5003.com”,
“changeOrigin”: true
}, {
“src”: “/kapis”,
“target”: “http://127.0.0.1:10000”,
“changeOrigin”: true
}, {
“src”: “/unicom2”,
“target”: “http://115.231.156.62”,
“changeOrigin”: true
}, {
“src”: “/king”,
“target”: “http://127.0.0.1:8088”,
“changeOrigin”: true
}]
};