1

If I send a JSON from frontend angular.js to backend node.js, it give me an error: TypeError: Cannot read property username of undefined. I'm using also Express.

Frontend (Angular.js):

var username_data = $scope.LoginUsername;
var password_data = $scope.LoginPassword;
var data = {username : username_data, password : password_data};

$http.post('/api/login', data)
.then(function (res) {
    //to do...
});

Backend (node.js) with Restful API:

app.post('/api/login', function(req, res) {
    console.log(req.data.username);
    console.log(req.data.password);
});

1 Answer 1

1

It means data does not exists, just try req.body instead

app.post('/api/login', function(req, res) {
    console.log(req.body.username);
    console.log(req.body.password);
});
Sign up to request clarification or add additional context in comments.

4 Comments

console.log return undefined
can you post what it is showing when you console.log(req);
__onFinished: { [Function: listener] queue: [Array] }, [Symbol(outHeadersKey)]: { 'x-powered-by': [Array], vary: [Array] } }, _startAt: [ 12994, 141275677 ], _startTime: 2018-01-13T10:30:26.601Z, _remoteAddress: '::ffff:127.0.0.1', body: { username: 'cccccc', password: 'dddd' }, _body: true, length: undefined, read: [Function], originalMethod: 'POST', route: Route { path: '/api/login', stack: [ [Object] ], methods: { post: true } } } (node:5072) [DEP0013] DeprecationWarning: Calling an asynchronous function witho ut callback is deprecated.
sorry if i was not clear in the first time, was posting from mobile

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.