78 lines
2.4 KiB
JavaScript
78 lines
2.4 KiB
JavaScript
import express from "express";
|
||
import path from "path";
|
||
import { getDomObj } from "./window"
|
||
import { render } from "./render";
|
||
import { url, zoneUrl } from "../src/ssrUrl";
|
||
const { createProxyMiddleware } = require('http-proxy-middleware');
|
||
import Logger from "./log";
|
||
|
||
// 转发的后端服务的端口
|
||
const rubyPort = process.env.PORT || 8081
|
||
|
||
const app = express();
|
||
app.use('/build', express.static('build'));
|
||
|
||
const options = (target) => {
|
||
return {
|
||
target: target,
|
||
changeOrigin: false, // 允许在请求头中更改主机
|
||
timeout: 30000,
|
||
onProxyRes: (proxyRes, req, res) => {
|
||
// 代理成功后输出日志
|
||
Logger.info(`Proxy to ${req.url} responded with status ${proxyRes.statusCode}`);
|
||
},
|
||
onError: (err, req, res) => {
|
||
// 代理过程中出错时输出日志
|
||
Logger.error(`Error proxying ${req.url}:`, err.message);
|
||
res.status(500).send('Proxy error');
|
||
},
|
||
};
|
||
}
|
||
|
||
const proxy = createProxyMiddleware(options(`http://localhost:${ rubyPort }`));
|
||
// const proxy = createProxyMiddleware(options(url));
|
||
|
||
|
||
// 本地调试用设置代理
|
||
// app.use(['/api/zone', '/api/cms'], (req, res) => {
|
||
// const proxy = createProxyMiddleware(options(zoneUrl));
|
||
// proxy(req, res);
|
||
// });
|
||
|
||
// 本地调试用设置代理
|
||
// app.use(['/api', '/images', '/system', '/favicon', '/robots.txt', '/sitemap*.xml', '/sitemap*.txt', '/favicon.ico', '/admins', '/assets', '/attachments', '/oauth'], (req, res) => {
|
||
// proxy(req, res);
|
||
// });
|
||
|
||
// 设置代理
|
||
app.use(['/api', '/admins', '/attachments', '/oauth'], (req, res) => {
|
||
proxy(req, res);
|
||
});
|
||
|
||
// 中间件,用于排除特定的路径
|
||
function excludePath(req, res, next) {
|
||
// 检查请求的路径是否需要被排除
|
||
if (req.path.includes('/build/')) {
|
||
// 如果是,直接结束请求,不调用下一个中间件或路由处理器
|
||
res.status(404).send('This path is excluded.');
|
||
} else {
|
||
// 如果不是,继续执行下一个中间件或路由处理器
|
||
next();
|
||
}
|
||
}
|
||
// 应用中间件到所有路由
|
||
app.use(excludePath);
|
||
|
||
// 匹配路径,匹配到的返回处理后的html,没匹配到转发到后端
|
||
app.get('*',async function (req,res) {
|
||
global.domObj = getDomObj()
|
||
const renderHead = await render(req,res)
|
||
if (!renderHead) {
|
||
proxy(req, res);
|
||
}
|
||
})
|
||
|
||
const port = 3000
|
||
|
||
console.log(`\n==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.\n`)
|
||
app.listen(port, '0.0.0.0'); |