Files
weiguang-jewelry-ledger/新账系统/server/middleware/body.js
T

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

22 lines
708 B
JavaScript
Raw Normal View History

'use strict';
const { fail } = require('../../core/ledger');
const LIMIT = 300000;
// 按字节累计、超限即拒绝;收齐后一次性按 UTF-8 解码,避免多字节字符被块边界截断。
async function readBody(req, afterRead) {
const chunks = [];
let size = 0;
for await (const chunk of req) {
const buffer = typeof chunk === 'string' ? Buffer.from(chunk) : chunk;
size += buffer.length;
if (size > LIMIT) fail('内容过大', 413);
chunks.push(buffer);
}
afterRead?.();
const raw = Buffer.concat(chunks, size).toString('utf8');
try {
return JSON.parse(raw || '{}');
} catch {
fail('请求内容不是有效JSON');
}
}
module.exports = { readBody };