Shai
Shai

Reputation: 77

Can't get POST data in NodeJS from Angular app

I can't get the params from a POST method I made from an Angular app. I tried looking for an answer here and even copy/paste some examples but nothing seems to work.

The Node code:

var express = require('express');
var app = express();
var bodyParser = require('body-parser');

app.use(bodyParser.urlencoded({ extended: false }));
app.use(express.static('public_html'));

app.post('/test', function (request, response) {
  console.log(request.body.name)
  response.status(201).json(request.body.name);
});

app.listen(8787,function() {
    console.log('Listening on 8787');
});

The Angular code:

$scope.postData = function() {

    $http.post('/test',{name: $scope.name}).success(function(data,status) {
        console.log('SUCCESS: ' + status);
        console.log(data);
    }).error(function(error) {
        console.log('ERROR');
        console.log(data);
    })
}

I can see on the network panel of the developer tools that the data is sent and I even get the http code of 201 as expected but I'm not getting back the reply. In the console.log() of the post route in NodeJS I'm getting undefined as well. Seems like the body-parser is not working or I'm missing something else.

Upvotes: 1

Views: 1062

Answers (2)

KimCrab
KimCrab

Reputation: 2361

I had a same problem and this is how I solved it.

Change this part

response.status(201).json(request.body.name);

to

response.write(request.body.name);

response.end();

I hope it will solve your problem. but I'm not sure why it is working. I hope someone explain it.

Upvotes: 0

oznu
oznu

Reputation: 1694

The angular $http.post function will send a JSON body rather than a urlencoded body.

Add this middleware to parse JSON objects:

app.use(bodyParser.json());

Upvotes: 1

Related Questions