Update JsonPost.js example

This commit is contained in:
Alex Hultman 2019-02-21 14:24:29 +01:00
parent ccd8050011
commit d8937c61d8

View File

@ -19,8 +19,8 @@ const app = uWS./*SSL*/App({
res.end('Thanks for this json!'); res.end('Thanks for this json!');
}, () => { }, () => {
/* Request was prematurely aborted, stop reading */ /* Request was prematurely aborted or invalid or missing, stop reading */
console.log('Ugh!'); console.log('Invalid JSON or no data at all!');
}); });
}).listen(port, (token) => { }).listen(port, (token) => {
@ -38,10 +38,25 @@ function readJson(res, cb, err) {
res.onData((ab, isLast) => { res.onData((ab, isLast) => {
let chunk = Buffer.from(ab); let chunk = Buffer.from(ab);
if (isLast) { if (isLast) {
let json;
if (buffer) { if (buffer) {
cb(JSON.parse(Buffer.concat([buffer, chunk]))); try {
json = JSON.parse(Buffer.concat([buffer, chunk]));
} catch (e) {
/* res.close calls onAborted */
res.close();
return;
}
cb(json);
} else { } else {
cb(JSON.parse(chunk)); try {
json = JSON.parse(chunk);
} catch (e) {
/* res.close calls onAborted */
res.close();
return;
}
cb(json);
} }
} else { } else {
if (buffer) { if (buffer) {