From 2c47d357f6e56951180f67c18a15dbdc377a4edd Mon Sep 17 00:00:00 2001 From: aurieh <auriteh@gmail.com> Date: Sat, 31 Dec 2016 14:09:17 +0200 Subject: [PATCH] Fix body parser --- index.js | 45 ++++++++++++++++++++++++--------------------- 1 file changed, 24 insertions(+), 21 deletions(-) diff --git a/index.js b/index.js index 801818a..ca3641b 100644 --- a/index.js +++ b/index.js @@ -46,34 +46,37 @@ app.use(function* (next) { yield next; return; } - if (!this.headers['application/json']) { + if (this.headers['content-type'] || !~this.headers['content-type'].indexOf('application/json')) { this.status = 400; this.body = { code: 400, message: 'invalid content type, should be application/json' }; - yield next; - return; + return yield next; } - let rawData = ''; - - this.req.on('data', chunk => { - rawData += chunk.toString(); - }); - this.req.on('end', () => { - try { - this.req.body = JSON.parse(rawData); - next(); - return; - } catch (err) { - this.body = { - code: 400, - message: 'invalid body data, should be a valid JSON string' - }; - this.status = 400; - } - }); + try { + const body = yield new Promise((resolve, reject) => { + let rawData = ''; + this.req.on('data', chunk => { + rawData += chunk.toString(); + }); + this.req.on('end', () => { + try { + resolve(JSON.parse(rawData)); + } catch (err) { + reject({ + code: 400, + message: 'invalid body data, should be a valid JSON string' + }); + } + }); + }); + this.req.body = body; + } catch (e) { + this.status = 400; + this.body = e; + } }); /** -- GitLab