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() {
|
constructor() {
|
||||||
this.expressAPP = express();
|
this.expressAPP = express();
|
||||||
this.expressAPP.use(express.urlencoded({extended: true, limit: "500mb"}));
|
this.expressAPP.use(express.urlencoded({extended: true, limit: "5000mb"}));
|
||||||
// 自定义JSON解析中间件,避免有些人不填写Content-Type导致无法解析JSON
|
this.expressAPP.use((req, res, next) => {
|
||||||
const customJsonParser = (req, res, next) => {
|
// 兼容处理没有带content-type的请求
|
||||||
// 确保我们只处理`POST`请求
|
// log("req.headers['content-type']", req.headers['content-type'])
|
||||||
if (req.method === 'POST') {
|
req.headers['content-type'] = 'application/json';
|
||||||
// 临时存储请求体数据
|
const originalJson = express.json({limit: "5000mb"});
|
||||||
let data = '';
|
// 调用原始的express.json()处理器
|
||||||
|
originalJson(req, res, (err) => {
|
||||||
// 监听data事件以收集数据片段
|
if (err) {
|
||||||
req.on('data', chunk => {
|
log("Error parsing JSON:", err);
|
||||||
data += chunk;
|
return res.status(400).send("Invalid JSON");
|
||||||
});
|
|
||||||
|
|
||||||
// 数据接收完成
|
|
||||||
req.on('end', () => {
|
|
||||||
if (data) {
|
|
||||||
try {
|
|
||||||
// 尝试解析JSON
|
|
||||||
req.body = JSON.parse(data);
|
|
||||||
} catch (error) {
|
|
||||||
// 解析失败,返回错误响应
|
|
||||||
return res.status(400).send('Invalid JSON');
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
next();
|
next();
|
||||||
});
|
});
|
||||||
} else {
|
});
|
||||||
next();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
this.expressAPP.use(customJsonParser);
|
|
||||||
}
|
}
|
||||||
|
|
||||||
authorize(req: Request, res: Response, next: () => void) {
|
authorize(req: Request, res: Response, next: () => void) {
|
||||||
|
Loading…
x
Reference in New Issue
Block a user