From 83dc1abd4a476b993f1433fef98ddc0bb57cb48e Mon Sep 17 00:00:00 2001 From: linyuchen Date: Mon, 11 Mar 2024 11:44:17 +0800 Subject: [PATCH] refactor: optimize json parser --- src/common/server/http.ts | 44 +++++++++++++-------------------------- 1 file changed, 14 insertions(+), 30 deletions(-) diff --git a/src/common/server/http.ts b/src/common/server/http.ts index d971b2e..7194649 100644 --- a/src/common/server/http.ts +++ b/src/common/server/http.ts @@ -11,37 +11,21 @@ export abstract class HttpServerBase { constructor() { this.expressAPP = express(); - this.expressAPP.use(express.urlencoded({extended: true, limit: "500mb"})); - // 自定义JSON解析中间件,避免有些人不填写Content-Type导致无法解析JSON - const customJsonParser = (req, res, next) => { - // 确保我们只处理`POST`请求 - if (req.method === 'POST') { - // 临时存储请求体数据 - let data = ''; - - // 监听data事件以收集数据片段 - req.on('data', chunk => { - data += chunk; - }); - - // 数据接收完成 - req.on('end', () => { - if (data) { - try { - // 尝试解析JSON - req.body = JSON.parse(data); - } catch (error) { - // 解析失败,返回错误响应 - return res.status(400).send('Invalid JSON'); - } - } - next(); - }); - } else { + this.expressAPP.use(express.urlencoded({extended: true, limit: "5000mb"})); + this.expressAPP.use((req, res, next) => { + // 兼容处理没有带content-type的请求 + // log("req.headers['content-type']", req.headers['content-type']) + req.headers['content-type'] = 'application/json'; + const originalJson = express.json({limit: "5000mb"}); + // 调用原始的express.json()处理器 + originalJson(req, res, (err) => { + if (err) { + log("Error parsing JSON:", err); + return res.status(400).send("Invalid JSON"); + } next(); - } - }; - this.expressAPP.use(customJsonParser); + }); + }); } authorize(req: Request, res: Response, next: () => void) {