thatDubstepSound
thatDubstepSound

Reputation: 357

nodejs won't accept post from angularjs

I have a nodeJS set up on one server, and my AngularJS set up on another. I'm trying to post data from my AngularJS to the NodeJS as a test, and simply have it bounce back. But whenever I check the req.body inside my NodeJS, it is always empty. Here is the code in Nodejs:

var express = require("express");
var logfmt = require("logfmt");
var mongo = require('mongodb');
var app = express();

app.use(logfmt.requestLogger());

var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
   console.log("Listening on " + port);
});

app.all('*', function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
   res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
   next();
});


app.post('/', function(req, res, next) {
   res.send(req.body); 
});     

No matter what i send from my AngularJS app, the req.body always returns empty. Here is the snippet of corresponding code in my AngularJS:

var tempdata = { "test": "testing" }; 

$scope.searchnow = function () {
   $http.post("http://afternoon-savannah-3595.herokuapp.com/", tempdata)
     .success(function (data) {
        console.log(data); 
     }).error(function () {
        console.log("something went wrong");
    })
}

Any help would be appreciated.

Upvotes: 0

Views: 720

Answers (1)

SomeKittens
SomeKittens

Reputation: 39522

You'll need to install and use body-parser for this to work:

npm install --save body-parser

and in app.js (I also moved your listen call to the bottom of the file)

var express = require("express");
var logfmt = require("logfmt");
var mongo = require('mongodb');
var bodyparser = require('body-parser');
var app = express();

app.use(logfmt.requestLogger());
app.use(bodyparser());

app.all('*', function(req, res, next) {
   res.header("Access-Control-Allow-Origin", "*");
   res.header('Access-Control-Allow-Headers', 'Content-Type,X-Requested-With');
   res.header('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
   next();
});


app.post('/', function(req, res, next) {
   res.send(req.body); 
});

var port = Number(process.env.PORT || 5000);
app.listen(port, function() {
   console.log("Listening on " + port);
});

Upvotes: 2

Related Questions