Parsing JSON in Express without BodyParser
I think the problem like to get rawBody in express.
Just like this:
app.use(function(req, res, next){ var data = ""; req.on('data', function(chunk){ data += chunk}) req.on('end', function(){ req.rawBody = data; req.jsonBody = JSON.parse(data); next(); })})
And you need catch the error when parse the string to json and need to judge the Content-type
of the Req
.
Good luck.
another way that worked with me by collecting all chunks into an array and parsing the concatenated chunks.
app.use("/", (req, res, next)=>{ const body = []; req.on("data", (chunk) => { console.log(chunk); body.push(chunk); }); req.on("end", () => { const parsedBody = Buffer.concat(body).toString(); const message = parsedBody.split('=')[1]; console.log(parsedBody); console.log(message); }); console.log(body);});