0

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.

0

1 Answer 1

2

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);
});
Sign up to request clarification or add additional context in comments.

Comments

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.