add bodysize

This commit is contained in:
2026-06-07 18:47:39 +08:00
parent 8fd1606424
commit 76c2f17229
3 changed files with 43 additions and 6 deletions

View File

@@ -1,6 +1,7 @@
# Server Configuration # Server Configuration
SERVER_PORT=5001 SERVER_PORT=5001
REACT_APP_API_BASE_URL=http://localhost:5001 REACT_APP_API_BASE_URL=http://localhost:5001
BODY_LIMIT=5mb
# Client Configuration # Client Configuration
CLIENT_PORT=3001 CLIENT_PORT=3001
REACT_APP_CLIENT_URL=http://localhost:3001 REACT_APP_CLIENT_URL=http://localhost:3001

View File

@@ -1,6 +1,7 @@
# 服务器配置 # 服务器配置
PORT=5001 PORT=5001
NODE_ENV=development NODE_ENV=development
BODY_LIMIT=5mb
# 数据库配置 # 数据库配置
MONGODB_URI=mongodb://localhost:27017/typeskill MONGODB_URI=mongodb://localhost:27017/typeskill

View File

@@ -25,11 +25,13 @@ import sudokuRouter from './routes/sudoku';
// 加载环境变量 // 加载环境变量
dotenv.config(); dotenv.config();
const BODY_LIMIT = process.env.BODY_LIMIT || '5mb';
const app = express(); const app = express();
// 中间件配置 // 中间件配置
app.use(express.json()); app.use(express.json({ limit: BODY_LIMIT }));
app.use(express.urlencoded({ extended: true })); app.use(express.urlencoded({ extended: true, limit: BODY_LIMIT }));
app.use(cors()); app.use(cors());
// 静态文件服务 - 优先处理 public 目录下的静态文件 // 静态文件服务 - 优先处理 public 目录下的静态文件
@@ -202,7 +204,40 @@ app.use((req, res, next) => {
// 错误处理中间件 // 错误处理中间件
app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => { 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!'); res.status(500).send('Something broke!');
}); });