const express = require('express');
|
const { createProxyMiddleware } = require('http-proxy-middleware');
|
const app = express();
|
const path = require('path');
|
const fs = require('fs');
|
const config = require(path.join(__dirname, '../dist/config'));
|
|
// proxy 中间件的选择项
|
const options = {
|
target: config.INTERFACE_SERVER_PATH, // 目标服务器 host
|
changeOrigin: true, // 默认false,是否需要改变原始主机头为目标URL
|
// ws: true, // 是否代理websockets
|
pathRewrite: {
|
'^/app': '/app', // 重写请求,比如我们源访问的是api/old-path,那么请求会被解析为/api/new-path
|
},
|
logLevel: 'debug',
|
onProxyReq: (proxyReq, req, res) => {
|
console.log('fasongqingqiu')
|
proxyReq.setHeader('X-Forwarded-For', getClientIp(req));
|
},
|
onError: (err, req, res) => {
|
res.writeHead(500, {
|
'Content-Type': 'text/plain',
|
});
|
res.end('Something went wrong. And we are reporting a custom error message.');
|
}
|
};
|
|
const exampleProxy = createProxyMiddleware(options);
|
const staticPath = config.NODE_ENV == 'production' ? '../dist/prod' : config.NODE_ENV == 'test' ? '../dist/test' : '../dist/dev';
|
app.use(express.static(path.join(__dirname, staticPath), { index: "" }));
|
|
app.use('/app', exampleProxy);
|
// app.get('*', function(req, res) {
|
// let PcUrlBrief = '51huishen.com';
|
// let PcUrl = 'www.51huishen.com';
|
// let MobileUrl = 'm.51huishen.com';
|
// //获取当前url地址
|
// let url = req.get('host')
|
// let deviceAgent = req.headers["user-agent"].toLowerCase();
|
// let agentID = deviceAgent.match(/(iphone|ipod|ipad|android)/);
|
// if (agentID) {
|
// //移动端
|
// if (url == PcUrl || url == PcUrlBrief) {
|
// res.redirect('https://' + MobileUrl + req.url);
|
// return;
|
// }
|
// } else {
|
// //pc端
|
// if (url == MobileUrl) {
|
// res.redirect('https://' + PcUrl + req.url);
|
// return;
|
// }
|
// }
|
// const indexPath = config.NODE_ENV == 'production' ? '../dist/prod/index.html' : config.NODE_ENV == 'test' ?
|
// '../dist/test/index.html' : '../dist/dev/index.html';
|
// const html = fs.readFileSync(path.resolve(__dirname, indexPath), 'utf-8');
|
// res.send(html);
|
|
// // res.sendFile(path.join(__dirname, '../dist/index.html'));
|
// });
|
app.get('*', function(req, res) {
|
const indexPath = config.NODE_ENV == 'production' ? '../dist/prod/index.html' : config.NODE_ENV == 'test' ?
|
'../dist/test/index.html' : '../dist/dev/index.html';
|
const html = fs.readFileSync(path.resolve(__dirname, indexPath), 'utf-8');
|
res.send(html);
|
});
|
app.listen(config.APP_SERVER_PORT, '0.0.0.0', function(err) {
|
if (err) {
|
console.log('start failed:' + err);
|
} else {
|
console.log('start success ...');
|
}
|
});
|
|
let getClientIp = function(req) {
|
return req.headers['X-Forwarded-For'] ||
|
req.connection.remoteAddress ||
|
req.socket.remoteAddress ||
|
req.connection.socket.remoteAddress || '';
|
};
|