forgeplus-react/server/index.js

67 lines
2.2 KiB
JavaScript
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

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: process.env.NODE_ENV === 'dev' ? true : false, // 服务器不允许在请求头中更改主机
timeout: 30000,
secure: process.env.NODE_ENV === 'dev' ? false : true, // 忽略证书验证
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');
},
};
}
let proxy
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);
});
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 {
proxy = createProxyMiddleware(options(`http://localhost:${ rubyPort }`));
// 设置代理
app.use(['/api', '/admins', '/attachments', '/oauth', '/competitions', '/projects', '/auth', '/settings'], (req, res) => {
proxy(req, res);
});
}
// 匹配路径匹配到的返回处理后的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');