forgeplus-react/server/index.js

67 lines
2.2 KiB
JavaScript
Raw Normal View History

2023-12-26 13:49:10 +08:00
import express from "express";
2024-04-19 15:20:52 +08:00
import path from "path";
2024-01-19 17:34:43 +08:00
import { getDomObj } from "./window"
import { render } from "./render";
2024-01-31 11:14:52 +08:00
import { url, zoneUrl } from "../src/ssrUrl";
2023-12-29 16:43:14 +08:00
const { createProxyMiddleware } = require('http-proxy-middleware');
2024-04-23 14:31:31 +08:00
import Logger from "./log";
2023-12-26 13:49:10 +08:00
2024-04-23 16:21:05 +08:00
// 转发的后端服务的端口
const rubyPort = process.env.PORT || 8081
2023-12-26 13:49:10 +08:00
const app = express();
2023-12-29 16:43:14 +08:00
app.use('/build', express.static('build'));
2024-04-23 14:31:31 +08:00
2024-01-31 11:14:52 +08:00
const options = (target) => {
return {
target: target,
changeOrigin: process.env.NODE_ENV === 'dev' ? true : false, // 服务器不允许在请求头中更改主机
2024-01-31 11:14:52 +08:00
timeout: 30000,
secure: process.env.NODE_ENV === 'dev' ? false : true, // 忽略证书验证
2024-04-23 14:31:31 +08:00
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');
},
2024-01-31 11:14:52 +08:00
};
}
2024-05-11 10:47:59 +08:00
let proxy
2024-04-17 10:41:56 +08:00
if (process.env.NODE_ENV === 'dev') {
// 本地调试用设置代理
proxy = createProxyMiddleware(options(url));
app.use(['/api/zone', '/api/cms'], (req, res) => {
const proxy = createProxyMiddleware(options(zoneUrl));
proxy(req, res);
});
2024-05-11 16:18:22 +08:00
app.use(['/api', '/images', '/system', '/favicon', '/robots.txt', '/sitemap*.xml', '/sitemap*.txt', '/favicon.ico', '/admins', '/assets', '/attachments', '/oauth', '/settings'], (req, res) => {
proxy(req, res);
});
} else {
2024-05-11 10:47:59 +08:00
proxy = createProxyMiddleware(options(`http://localhost:${ rubyPort }`));
// 设置代理
2024-05-11 16:18:22 +08:00
app.use(['/api', '/admins', '/attachments', '/oauth', '/competitions', '/projects', '/auth', '/settings'], (req, res) => {
proxy(req, res);
});
}
2024-04-17 10:41:56 +08:00
2023-12-29 16:43:14 +08:00
2023-12-26 13:49:10 +08:00
2024-04-19 14:18:56 +08:00
// 匹配路径匹配到的返回处理后的html没匹配到转发到后端
2024-04-17 14:31:40 +08:00
app.get('*',async function (req,res) {
2024-01-19 17:34:43 +08:00
global.domObj = getDomObj()
2024-04-17 14:31:40 +08:00
const renderHead = await render(req,res)
if (!renderHead) {
2024-04-17 10:10:27 +08:00
proxy(req, res);
}
2023-12-26 13:49:10 +08:00
})
2024-01-15 11:44:36 +08:00
const port = 3000
2023-12-26 17:27:28 +08:00
console.log(`\n==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.\n`)
2024-01-12 10:56:03 +08:00
app.listen(port, '0.0.0.0');