JSON parsing in express without BodyParser

I am trying to write a simple express server that accepts incoming JSON (POST), parses JSON and assigns the request body. The trick is I can't use bodyparser. Below is my server with a simple middleware function passed to app.use

Problem: whenever I send fictitious POST requests to my server with a superant (npm package that allows sending JSON through the terminal), my server shuts down. I wrote an HTTP server in a similar way using req.on ('data') ... so I'm at a dead end. Any tips?

const express = require('express'); const app = express(); function jsonParser(req, res, next) { res.writeHead(200, {'Content-Type:':'application/json'}); req.on('data', (data, err) => { if (err) res.status(404).send({error: "invalid json"}); req.body = JSON.parse(data); }); next(); }; app.use(jsonParser); app.post('/', (req, res) => { console.log('post request logging message...'); }); app.listen(3000, () => console.log('Server running on port 3000')); 
+7
source share
2 answers

I think the problem is getting rawBody to express.

Similar:

 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 to catch the error while parsing the string in json and need to judge the Content-type Req .

Good luck.

+19
source

another way that worked with me, collecting all the pieces into an array and analyzing the connected pieces.

 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); }); 
0
source

Source: https://habr.com/ru/post/1241098/


All Articles