Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unable to get $http.post request data in Node.js res.body

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.

like image 495
Rahul Sagore Avatar asked Dec 01 '15 09:12

Rahul Sagore


1 Answers

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
});
like image 82
boehm_s Avatar answered Oct 12 '22 13:10

boehm_s