forgeplus-react/server/index.js

59 lines
1.7 KiB
JavaScript

import express from "express";
import { getDomObj } from "./window"
import { render } from "./render";
import { url, zoneUrl } from "../src/ssrUrl";
const { createProxyMiddleware } = require('http-proxy-middleware');
const app = express();
app.use('/build', express.static('build'));
const options = (target) => {
return {
target: target,
changeOrigin: true, // 允许在请求头中更改主机
timeout: 30000,
// 只改head版本不需要重写ua
// headers: {
// 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36 Edg/121.0.0.0'
// }
};
}
const proxy = createProxyMiddleware(options('http://localhost:8080'));
// 设置代理
// app.use(['/api/zone', '/api/cms'], (req, res) => {
// proxy(req, res);
// });
// 设置代理
app.use(['/api', '/images', '/system', '/favicon', '/robots.txt', '/sitemap*.xml', '/sitemap*.txt'], (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);
app.get('*',function (req,res) {
global.domObj = getDomObj()
if (!render(req,res)) {
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');