mirror of
https://github.com/LLOneBot/LLOneBot.git
synced 2024-11-22 01:56:33 +00:00
refactor: optimize json parser
This commit is contained in:
parent
4cabb9696e
commit
83dc1abd4a
@ -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) {
|
||||
|
Loading…
x
Reference in New Issue
Block a user