user1189352 user1189352 - 24 days ago 12
Node.js Question

Passing Angular variable to Express backend through POST

req.body
is always empty. I'm not sure what I'm doing wrong? I tried adding content-type headers as json but that didn't do anything either. Can someone lead me in the correct direction please? Thank you

EDIT: just for clarification purposes, my Angular frontend hits the backend function successfully, but req.body is empty. If I understand everything correctly, if I'm using the 'body-parser' library, it should be passed in through post through 'req.body'. I'm just not seeing that though and I'm not sure why.

EDIT2: I have the body parser code in my app.js but the backend routing in a index.js file, does that have anything to do with it?

EDIT3: app.js http://pastebin.com/9vNgf0Nd
index.js http://pastebin.com/icLa3e2X

ANGULAR FRONTEND

service.registerAccount = function(account) {
console.log(account); //account = { userName: 'test', password: 'hello' }
return $http({
method: 'POST',
url: '/register',
data: { account: account },
headers: {'Content-Type': 'application/json'}
});
}


BACKEND (app.js)

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


BACKEND (index.js)

var express = require('express');
var router = express.Router();

router.post('/register', function(req, res) {
console.log(req.body);
};

Answer

Please remove this line

app.use(bodyParser.urlencoded({ extended: true }))

Also,

app.use(bodyParser.json());

have to be called before app.use('/', routes);

And make sure to add Content-Type: application/json to the request header

Comments