8

I am using Angular 1.3 and node.js 0.12.2 for a project. I am hitting the node.js api using

$http.post("url", request_data){}

And on server side using this:

console.log(req.body)

But everytime the api gets called, it gets empty object {} for request_data , Unable to get what the problem is. I have used body_parser like this:

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

Have also tried adding content-type header in angular $http as:

headers : {'Content-Type': 'applicatio n/x-www-form-urlencoded'}

But not getting request data.

EDIT:

Node.js code :

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

Note: Developer Tool's network tab showing the data, I am sending, in request header correctly, but node.js server not receiving in req.body. In POSTman getting data is correctly in response.

solarissmoke
  • 30,039
  • 14
  • 71
  • 73
Rahul Sagore
  • 1,588
  • 2
  • 26
  • 47

2 Answers2

1

some ideas :

  • Maybe an URL error ? Make sure you aren't using a prefix like app.use('/api', router);
  • Look at the Content-Type :

application/x-www-form-urlencoded --> 'var1="SomeValue"&var2='+SomeVariable application/json;charset=UTF-8 --> {var1:"SomeValue", var2:SomeVariable}

  • You could use $http more explicitly :

$http({
  url: '...',
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded'
  },
  data: 'var1="SomeValue"&var2='+SomeVariable
});
boehm_s
  • 5,254
  • 4
  • 30
  • 44
0

My best guess is that your angular $http request URL is pointing to a bad end-point.

Angularjs

// data to post nodejs server
var _data = {
    'message': 'Can I help you?'
};


// angularjs $http post request
$http.post('/api/url', _data).then(function(respond){
    // if success
    console.log(respond);
}, function(error){
    // if an error
    console.error(error);
});

Nodejs

// router function
function something(req, res) {

    // console.log the request body
    console.log(req.body);

    // respond JSON object
    var _respond = {
        'status': 200
    };

    // expressjs respond a JSON with status code 200
    res.status(200).json(_respond);
}

// register route URL
router.post('/api/url', something);

Note that the code end point URLs are same : /api/url

Therefore as your code sample in above question, you'r missing a /

Malindu
  • 135
  • 1
  • 12
  • No, end point is correct, I used dummy url to explain the problem, Node.js is able to get the request. I am using $.ajax, instead of $http. Still there is problem with the data format. So we changed the node.js code. to handle the requested data. – Rahul Sagore Dec 04 '15 at 11:40
  • After using $.ajax, node.js got the header data, but it was not showing the empty array. – Rahul Sagore Dec 04 '15 at 11:41