Quickee Quickee - 1 month ago 12
JSON Question

Node js express can't parse body after routes moved into own folder

Moved routes into their own folder now I cant parse the response body. Controller sends body correctly. App worked correctly when routes were in server js file.

Server.js BEFORE

var express = require('express');
var app = express();
var routes = require('./routes/routes.js');

app.use('/',routes);
app.use(express.static(__dirname + '/public'));
app.use('/bootstrap', express.static(__dirname + '/public/bower_components/bootstrap/dist'));
app.use('/jquery', express.static(__dirname + '/public/bower_components/jquery/dist'));
app.use('/angular', express.static(__dirname + '/public/bower_components/angular'));
app.use('/controllers', express.static(__dirname + '/public/controllers'));


Routes.js

var express = require('express');
var app = express();

var bodyParser = require('body-parser');
var ObjectId = require('mongojs').ObjectID;
var mongojs = require('mongojs');
var db = mongojs('contactlist',['contactlist'])
var router = express.Router();
app.use(bodyParser.json());

router.put('/contactlist/:id',function(req,res){
console.log("req.body.name");//gives undefined
db.contactlist.findAndModify({
query:{_id: ObjectId(req.params.id)},
update:{ $set:{name:req.body.name,email:req.body.email,number:req.body.number}},
new: true},
function(err,doc){
res.json(doc);
});
});


module.exports = router;


Also, any thoughts as to why I have to append routes.js here instead of just / routes?

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


Folder Structure

-App
node_mods/
public/
index.html
controllers/
resources/
routes/
routes.js


Server.js AFTER

var express = require('express');
var app = express();

var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: true
}));

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

app.use('/',routes);
app.use(express.static(__dirname + '/public')); //look for static files js html css etc
app.use('/bootstrap', express.static(__dirname + '/public/bower_components/bootstrap/dist'));
app.use('/jquery', express.static(__dirname + '/public/bower_components/jquery/dist'));
app.use('/angular', express.static(__dirname + '/public/bower_components/angular'));
app.use('/controllers', express.static(__dirname + '/public/controllers'));

app.listen(3000);
console.log('server running on port 3000');

Answer

Your body is parsing after your route is called.

Pass your body-parser code in your main server file generally, it is server.js before all the routes.

Like this:

var app = express();
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: false
}));