bodyParser is not set error in Node.js

Asked

Viewed 397 times

0

I am trying to create an HTTP server that you will use bodyParser() to request the part of middleware before the handlers. But when trying to use it in the code, 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 part from bodyParser() as indicated by the current documentation and even by other websites when talking about it. But still, it’s not working. What could be making this mistake?

2 answers

0

0

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

Merge this at the beginning of the file:

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

(used const for good practice, but if you have an old version of Node use var)

  • Hello, thank you for posting the reply, it worked like a charm. I am currently using var in others, why is it better to use const ? Sorry I’m new to Node.js and even Javascript.

  • Take a look here: https://answall.com/a/206121/129

  • Incredible, much better to use const instead of var. And it serves perfectly to require the modules, since they will be constant. Thank you so much for the answer and patience, for being new in this part(Node.js and Javascript) errors and basic questions are until normal I believe.

  • @Monteiro great. If you want you can click to mark this answer as accepted.

  • Of course I will mark yes, I just have to wait for the site to allow me to give you the correct answer, it is necessary to wait a while to do this. I’ll look at more of your answers, you seem like a very good user when it comes to answering questions with pertinent answers.

  • @Monteiro I answer the best I know limited to the available time I have :)

Show 1 more comment

Browser other questions tagged

You are not signed in. Login or sign up in order to post.