zzyxyz_server/server.ts
ZZY fd945ecf6d ```
更改静态资源路径设置和服务顺序

在最新的提交中,我修改了`.gitignore`文件,以忽略额外的`static`目录。同时,在`default.env`文件中添加了`UPFRONT_PATH`变量,默认指向`./upfront`。在`server.ts`中,我更新了静态路径引用,使其使用`UPFRONT_PATH`变量,并明确`static`路径用于`/static`路由。这有助于更灵活地配置静态和前端资源路径,并优化服务器端的资源管理。
```
2024-09-22 23:17:31 +08:00

44 lines
1.4 KiB
TypeScript
Raw 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, { Application, Request, Response, NextFunction } from 'express';
import path from 'path';
import dotenv from 'dotenv';
dotenv.config();
process.env.ROOT_DIR = path.resolve(__dirname);
const env = process.env;
export const app = express();
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(require('cookie-parser')());
const dist = path.join(__dirname, env.UPFRONT_PATH ?? 'upfront');
// 静态资源服务假设你的dist目录包含了编译后的Vue应用
app.use(express.static(dist));
app.use('/static', express.static(path.join(__dirname, env.STATIC_PATH ?? 'static')))
import router from './src/routes/api';
app.use('/api', router);
// // catch 404 and forward to error handler
// app.use(function(req, res, next) {
// res.status(404);
// res.end('<h1>404 Not Found</h1>');
// });
// 所有未匹配到的请求都重定向到index.html,使用vue3的SPA匹配
app.get('*', (req: Request, res: Response) => {
res.sendFile(path.join(dist, '/index.html'));
});
// error handler
app.use(function(err: any, req: Request, res: Response, next: NextFunction) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = env.MOD === 'development' ? err : {};
console.log(err);
// render the error page
res.status(err.status || 500);
res.end('<h1>error</h1>');
});