Tyler B. Joudrey
Tyler B. Joudrey

Reputation: 491

Express and Mongoose: Cannot read property 'name' of undefined in Postman

I am attempting to create and insert 'user' json documents, defined in the model below, upon a POST request to localhost:3000/api/student. I am greeted with the following error using postman to send POST requests:

TypeError: Cannot read property 'name' of undefined
    at module.exports.makeStudent (/home/tyler/Dropbox/Projects/Curricula/API/controllers/student.js:17:22)
    at Layer.handle [as handle_request] (/home/tyler/Dropbox/Projects/Curricula/node_modules/express/lib/router/layer.js:95:5)
    at next (/home/tyler/Dropbox/Projects/Curricula/node_modules/express/lib/router/route.js:131:13)
    at Route.dispatch (/home/tyler/Dropbox/Projects/Curricula/node_modules/express/lib/router/route.js:112:3)
    at Layer.handle [as handle_request] (/home/tyler/Dropbox/Projects/Curricula/node_modules/express/lib/router/layer.js:95:5)
    at /home/tyler/Dropbox/Projects/Curricula/node_modules/express/lib/router/index.js:277:22
    at Function.process_params (/home/tyler/Dropbox/Projects/Curricula/node_modules/express/lib/router/index.js:330:12)
    at next (/home/tyler/Dropbox/Projects/Curricula/node_modules/express/lib/router/index.js:271:10)
    at Function.handle (/home/tyler/Dropbox/Projects/Curricula/node_modules/express/lib/router/index.js:176:3)
    at router (/home/tyler/Dropbox/Projects/Curricula/node_modules/express/lib/router/index.js:46:12)

Below are what I believe to be the relevant files

API/models/student.js

var mongoose = require('mongoose')
var studentSchema = new mongoose.Schema({
    name: {type: String, required: true},
    password: {type: String, required: true},
    classes: [Number]
    });

mongoose.model('Student', studentSchema);

API/controllers/student.js

var mongoose = require('mongoose');
var Student = mongoose.model('Student');

var sendJSONResponse = function(res, status, content){
   res.status(status);
   res.json({content});
}

module.exports.listStudents = function (req, res) {
   sendJSONResponse(res, 200, {"status" : "success"});
};
module.exports.studentIDLookup = function (req, res) { };
module.exports.studentAuth = function (req, res) { };
module.exports.studentNametoID = function (req, res) { };
module.exports.makeStudent = function (req, res) { 
   Student.create({
      name : req.body.name,
      password : req.body.password,
      email : req.body.email
   }, function(err, student){
      if(err){
         sendJSONResponse(res, 400, err)
      }
      else{//success
         sendJSONResponse(res, 201, student);
      }
   })
};
module.exports.deleteStudent = function (req, res) { };

app.js

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
require('./API/models/db')

var app = express();

// view engine setup
app.set('views', path.join(__dirname,'app','views'));
app.set('view engine', 'jade');

//routes
var indexRoute = require('./app/routes/index');
app.use('/', indexRoute);

var apiRoute = require('./API/routes/index.js')
app.use('/api', apiRoute);

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));


// catch 404 and forward to error handler
app.use(function(req, res, next) {
  var err = new Error('Not Found');
  err.status = 404;
  next(err);
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});


// Export app to module
module.exports = app;

Any insight to what I am doing wrong would be appreciated.

Upvotes: 2

Views: 7550

Answers (2)

Hassan Rezvan
Hassan Rezvan

Reputation: 11

first of all, you should install body-parser using npm:

npm i --save body-parser

then, add it to your js file like below:

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

for adding parser like urlencoded for post requests, use the below line:

const urlencodedParser = bodyParser.urlencoded({ extended: false });

finally, add urlencodedParser to your request as a middleware:

app.post('/', urlencodedParser, (req,res) => {})

Upvotes: 0

robertklep
robertklep

Reputation: 203304

The order in which you declare routes/middleware is incorrect:

//routes
var indexRoute = require('./app/routes/index');
app.use('/', indexRoute);

var apiRoute = require('./API/routes/index.js')
app.use('/api', apiRoute);

// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

This means that the body-parser middleware, which is used to populate req.body, won't get called for requests made to / and requests starting with /api, because those routes are declared before the body-parser middleware is declared.

The solution is to move body-parser (and logger as well, probably) to before the route declarations:

app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

//routes
var indexRoute = require('./app/routes/index');
app.use('/', indexRoute);

var apiRoute = require('./API/routes/index.js')
app.use('/api', apiRoute);

Upvotes: 7

Related Questions