Tomasz Gałkowski
Tomasz Gałkowski

Reputation: 1929

TypeError: Cannot read property 'body' of undefined after POST (MEAN)

I am trying to send POST data from AngularJS to Express. What I am doing at the moment is trying to send some POST stuff via curl.

I already tried sending the data. It gets send, I get 200 as a response. But whenever I try to access the data via body-parser through req.body I will get a 500 and the error that I posted at the very bottom.

I did a lot of research on that matter (past 4-5 hours...) and I think I checked the following common issues:

I surrender. StackOverflowers. Help me, please.

curl:

curl -X POST -H "Content-Type: application/json" -d '{"username": "gala", "email": "[email protected]", "password": "123"}' localhost:3000/users

express.js

// glowny plik przygotowujacy aplikacje express

// wczytanie zaleznosci
var express = require('express')
var stylus = require('stylus')
var parser = require('body-parser')
var morgan = require('morgan')
var compress = require('compression')
var methodOverride = require('method-override')

// przygotowanie aplikacji, obsluga middleware i na koncu zwrocenie obiektu aplikacji
module.exports = function() {
    var app = express()

    if (process.env.NODE_ENV === 'development') {
        app.use(morgan('dev'))
    } else if (process.env.NODE_ENV === 'production') {
        app.use(compress())
    }

    app.use(parser.urlencoded({ extended: true }))
    app.use(parser.json())

    app.use(methodOverride())

    // uzycie jade jako silnika szablonow dla html
    app.set('views', __dirroot + '/app/views')
    app.set('view engine', 'jade')

    require(__dirroot + '/app/routes/index.server.route.js')(app)
    require(__dirroot + '/app/routes/users.server.route.js')(app)

    // mozliwosci uzywania statycznych plikow z folderu /public
    app.use(express.static(__dirroot + '/public'))

    return app
}

users.server.route.js:

var users = require(__dirroot + '/app/controllers/users.server.controller.js')

module.exports = function(app) {
    app.route('/users').post(function() {
        users.create()
    })
}

users.server.controller.js:

var User = require('mongoose').model('User')

exports.create = function(req, res, next) {
    console.log(req.body)
}

Error message:

TypeError: Cannot read property 'body' of undefined
   at Object.exports.create (/home/gala/Projekty/cantr-crafting/app/controllers/users.server.controller.js:4:20)
   at /home/gala/Projekty/cantr-crafting/app/routes/users.server.route.js:5:15
   at Layer.handle [as handle_request] (/home/gala/Projekty/cantr-crafting/node_modules/express/lib/router/layer.js:82:5)
   at next (/home/gala/Projekty/cantr-crafting/node_modules/express/lib/router/route.js:110:13)
   at Route.dispatch (/home/gala/Projekty/cantr-crafting/node_modules/express/lib/router/route.js:91:3)
   at Layer.handle [as handle_request] (/home/gala/Projekty/cantr-crafting/node_modules/express/lib/router/layer.js:82:5)
   at /home/gala/Projekty/cantr-crafting/node_modules/express/lib/router/index.js:267:22
   at Function.proto.process_params (/home/gala/Projekty/cantr-crafting/node_modules/express/lib/router/index.js:321:12)
   at next (/home/gala/Projekty/cantr-crafting/node_modules/express/lib/router/index.js:261:10)
   at methodOverride (/home/gala/Projekty/cantr-crafting/node_modules/method-override/index.js:77:5) 

Upvotes: 5

Views: 30964

Answers (5)

salikin
salikin

Reputation: 1

In my case, I forgot to add

app.use(express.json());

in my index.ts

Upvotes: 0

Vibhanshu Garg
Vibhanshu Garg

Reputation: 1

const express = require("express");
const bodyParser = require("body-parser");

const app = express(); 
app.use(bodyParser.urlencoded({extended: true}));
app.get("/",function(req,res){
    res.sendFile(__dirname + "/index.html");
});

//Post processing after taking data from user..
app.post("/",function(req,res,next){
    var num1 = Number(req.body.num1);
    var num2 = Number(req.body.num2);
    var result = num1+num2;
    res.send("The result is "+ result);
});


// To create a server...
app.listen(3000, function(){
    console.log("Server started..3000");
});

I hope this code works for you as well. You may take help from above.

Upvotes: 0

Greko2015 GuFn
Greko2015 GuFn

Reputation: 589

This happen for me because I have added some testing script on the chrome console and it seems like there were interference. you clean your console manually or run your app in another instance f chrome.

Upvotes: 0

Laxminarayana
Laxminarayana

Reputation: 51

TypeError: Cannot read property 'body' of undefined after POST (MEAN) you will get this error when your localhost ip is changed or the requesting ip is not correct as you mentioned in the post url. I got the same error when I troubleshoot my ethernet. Then my Ip address was changed. So check your ip. It will work..

Upvotes: 2

Phil
Phil

Reputation: 164910

I don't use Node or Express much but shouldn't you at least pass req into users.create() from the route handler, ie

app.route('/users').post(function(req, res) {
    users.create(req, res)
})

or maybe even

app.route('/users').post(users.create);

Upvotes: 6

Related Questions