Creating api in node I get error: bodyparse is not defined

3

I am creating an API in node but I get the following error:

app.use(bodyParser.urlencoded({ extended: false }));  
        ^
ReferenceError: bodyParser is not defined
    at Object.<anonymous> (/home/keily/code/node-api-rest-example/app.js:7:9)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)
    at startup (node.js:129:16)
    at node.js:814:3

This is my app.js:

var express  = require("express"),  
    app      = express(),
    http     = require("http"),
    server   = http.createServer(app),
    mongoose = require('mongoose');

app.use(bodyParser.urlencoded({ extended: false }));  
app.use(bodyParser.json());  
app.use(methodOverride());

var router = express.Router();

router.get('/', function(req, res) {  
   res.send("Hello World!");
});

app.use(router);

mongoose.connect('mongodb://localhost:27017/tvshows', function(err, res) {  
  if(err) {
    console.log('ERROR: connecting to Database. ' + err);
  }
  app.listen(3000, function() {
    console.log("Node server running on http://localhost:3000");
  });
});
    
asked by LLaza 22.03.2016 в 17:16
source

1 answer

2

Node is javascript and in javascript all variables must be declared that includes the modules of your application. bodyParser is a module like any other so you must declare it with var and load the module with require . The same error gives you a clue because it is of type ReferenceError

  

The ReferenceError object represents an error when a variable that does not exist is referenced.

To fix it write:

var express    = require("express"),  
    app        = express(),
    http       = require("http"),
    server     = http.createServer(app),
    // ya tienes un identificador llamado bodyParser y en el cargas el módulo
    bodyParser = require('body-parser'),
    mongoose   = require('mongoose');

Please note that the module you are trying to load is installed with npm usually with a command

npm install body-parser

so this is in the node_modules folder and therefore the require call only needs the name of the module

var variable = require('modulo')

If you were to upload a file that you have written yourself, you have to use a relative path for tell you where to search

var variable = require('./myCodigo')

In neither case should you specify extension since the Node assumes by default the extension js , json and node in that order.

Finally remember that these modules have nothing special, they are simple objects exported using module.exports so you can do something like:

console.log(bodyParser)

and look at the methods that are included.

    
answered by 22.03.2016 / 17:46
source