Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing JSON in Express without BodyParser

I'm trying to write a simple express server that takes incoming JSON (POST), parses the JSON and assigns to the request body. The catch is I cannot use bodyparser. Below is my server with a simple middleware function being passed to app.use

Problem: whenever I send dummy POST requests to my server with superagent (npm package that lets you send JSON via terminal) my server times out. I wrote an HTTP server in a similar fashion using req.on('data')...so I'm stumped. Any advice?

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'));
like image 462
Jose Avatar asked Jan 21 '16 04:01

Jose


People also ask

Does Express need bodyParser?

This piece of middleware was called body-parser and used to not be part of the Express framework. The good news is that as of Express version 4.16+, their own body-parser implementation is now included in the default Express package so there is no need for you to download another dependency.

What happens if you don't use body-parser?

You will just lose the data, and request. body field will be empty. Though the data is still sent to you, so it is transferred to the server, but you have not processed it so you won't have access to the data.

What is the use of bodyParser in Express?

What Is Body-parser? Express body-parser is an npm module used to process data sent in an HTTP request body. It provides four express middleware for parsing JSON, Text, URL-encoded, and raw data sets over an HTTP request body.


1 Answers

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.

like image 134
deju Avatar answered Oct 12 '22 14:10

deju