bodyParser is not defined error in Node.js

1

I'm trying to create an HTTP server where it will use bodyParser() to request the middleware part before the handlers . But when trying to use it in code, it indicates error saying that it is not defined.

My code:

var http = require('http');
var connect = require('connect');
var logger = require('morgan');
var app = connect();
// setup the middlewares
app.use(logger(':method :req[content-type]'));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
// actually respond
app.use(function(req, res) {
res.end(JSON.stringify(req.body));
});
http.createServer(app).listen(8080);
  

bodyParser is not defined

I'm using the bodyParser() part as indicated by current documentation and even by other sites when talking about it. But it's still not working. What could be making this mistake?

    
asked by anonymous 11.06.2017 / 19:03

1 answer

0

You need to import this package into the file. bodyParser is an Express package, not a global Node.

Put this in the beginning of the file:

const bodyParser = require('body-parser');

(I used const for best practices, but if you have an older version of Node use var )

    
11.06.2017 / 19:04