var express = require('express');
//解构赋值
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.all('*', function (req, res, next) {
console.log("=====================")
console.log(req.url)
console.log("=====================")
res.header("Access-Control-Allow-Origin", req.headers.origin);//访问的主机名称
//为true的时候,前端必须传送cookie
res.header('Access-Control-Allow-Credentials','true'); //是否支持cookie跨域
res.header("Access-Control-Allow-Headers","Origin, X-Requested-With, Content-Type, Accept");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");//允许以下方法进行跨域请求
next();
});
const options1 = {
target: 'http://XXXX2:8081',
changeOrigin: true,
};
const options2 = {
target: 'http://XXXX2:8888',
changeOrigin: true,
pathRewrite: {
'^/api': '',
}
};
// 先匹配/api
const exampleProxy1 = createProxyMiddleware('/api', options2);
app.use(exampleProxy1);
const exampleProxy2 = createProxyMiddleware('/', options1);
app.use(exampleProxy2);
app.listen(3003, () => {
console.log(`server running @${3003}`);
});
前端访问本地192.168.xx.xx:3003