add bodysize
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
# 服务器配置
|
||||
PORT=5001
|
||||
NODE_ENV=development
|
||||
BODY_LIMIT=5mb
|
||||
|
||||
# 数据库配置
|
||||
MONGODB_URI=mongodb://localhost:27017/typeskill
|
||||
@@ -9,4 +10,4 @@ MONGODB_URI=mongodb://localhost:27017/typeskill
|
||||
JWT_SECRET=your_jwt_secret_key_here
|
||||
|
||||
# CORS配置
|
||||
CORS_ORIGIN=http://localhost:3000
|
||||
CORS_ORIGIN=http://localhost:3000
|
||||
|
||||
@@ -25,11 +25,13 @@ import sudokuRouter from './routes/sudoku';
|
||||
// 加载环境变量
|
||||
dotenv.config();
|
||||
|
||||
const BODY_LIMIT = process.env.BODY_LIMIT || '5mb';
|
||||
|
||||
const app = express();
|
||||
|
||||
// 中间件配置
|
||||
app.use(express.json());
|
||||
app.use(express.urlencoded({ extended: true }));
|
||||
app.use(express.json({ limit: BODY_LIMIT }));
|
||||
app.use(express.urlencoded({ extended: true, limit: BODY_LIMIT }));
|
||||
app.use(cors());
|
||||
|
||||
// 静态文件服务 - 优先处理 public 目录下的静态文件
|
||||
@@ -202,7 +204,40 @@ app.use((req, res, next) => {
|
||||
|
||||
// 错误处理中间件
|
||||
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => {
|
||||
console.error(err.stack);
|
||||
if (res.headersSent) {
|
||||
return next(err);
|
||||
}
|
||||
|
||||
if (
|
||||
err?.type === 'entity.too.large' ||
|
||||
err?.name === 'PayloadTooLargeError' ||
|
||||
err?.status === 413 ||
|
||||
err?.statusCode === 413
|
||||
) {
|
||||
console.warn('Request body too large:', {
|
||||
method: req.method,
|
||||
path: req.path,
|
||||
limit: BODY_LIMIT
|
||||
});
|
||||
return res.status(413).json({
|
||||
error: '请求体过大,请缩小单次提交内容',
|
||||
code: 'PAYLOAD_TOO_LARGE'
|
||||
});
|
||||
}
|
||||
|
||||
if (err?.type === 'entity.parse.failed') {
|
||||
console.error('Invalid JSON payload:', {
|
||||
method: req.method,
|
||||
path: req.path,
|
||||
message: err?.message
|
||||
});
|
||||
return res.status(400).json({
|
||||
error: '请求体格式无效',
|
||||
code: 'INVALID_JSON'
|
||||
});
|
||||
}
|
||||
|
||||
console.error(err?.stack || err);
|
||||
res.status(500).send('Something broke!');
|
||||
});
|
||||
|
||||
@@ -218,4 +253,4 @@ httpServer.listen(PORT, () => {
|
||||
console.log(`WebSocket server is ready`);
|
||||
console.log(`Environment:`, process.env.NODE_ENV);
|
||||
console.log(`REACT_APP_API_BASE_URL:`, process.env.REACT_APP_API_BASE_URL);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user