Rupinder Singh Rupinder Singh - 1 month ago 8
Node.js Question

Getting the error "bodyParser.json is not a function" in express app

I'm new to nodejs. While experimenting with express I got stuck. I'm just trying to test my app. I'm getting error while running server.js file. What am I missing?

Here is what console looks like...

C:\Users\rupindersingh\Dropbox\Works\worthlessmongo>node server.js
C:\Users\rupindersingh\Dropbox\Works\worthlessmongo\server.js:12
app.use(bodyParser.json());
^

TypeError: bodyParser.json is not a function
at Object.<anonymous> (C:\Users\rupindersingh\Dropbox\Works\worthlessmongo\server.js:12:20)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:974:3


Here is the pakage.json file

{
"name": "worthlessmongo",
"version": "1.0.0",
"description": "Just Tryin",
"main": "server.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node server.js"
},
"author": "",
"license": "ISC",
"dependencies": {
"body-parser": "^1.15.2",
"ejs": "^2.5.2",
"express": "^4.14.0",
"mongojs": "^2.4.0"
},
"devDependencies": {}
}


Server.js file is given below:

var express=require('express');
var path=require('path');
var bodyParser=('body-parser');

var index=require('./routes/index');

var app=express();
app.set('views',path.join(__dirname,'views'));
app.set('view engine','ejs');
app.engine('html',require('ejs').renderFile);
app.use(express.static(path.join(__dirname,'client')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use('/',index);
app.listen(3000,function(){
console.log('server started at port 3000');
});

Answer

You didn't use require when requiring body-parser

var express=require('express');
var path=require('path');
var bodyParser= require('body-parser');