Monday, April 9, 2012

Nodejs Express : request.body is null

Just had an other frustration with nodejs and this time again problem with header and fault was mine since i missed Content-type header.
While writing a nodeunit test ,

exports.parseRequest = function(test){
 http = require('http')
 test.expect(1)
 options = {
  "host": "127.0.0.1",
  "port": 3000,
  "path": "/movies/",
  "method": 'POST',
  "headers" : {
   Content-Type":"application/x-www-form-urlencoded"
  }
 }  
 request = http.request(options,function(response){
  console.log("Status "+response.statusCode)
  result = ''
  response.on('data',function(chunk){
   result += chunk
  })
  response.on('end',function(){
   response.destroy() 
   test.equal(result,"Hello World", "Reponse got")
   test.done();
   
  })
 })
 request.on('error' , function (connectionException){
   console.log("ERROR occured while creating connection to localhost "+connectionException);
 })
 request.write("data=sheat");
 request.end();
}
and there you go , i missed that content-type header on line 10 above and ended up wasting 30+mins to figure out why request.body is 'undefined'. >Make the header adjust according to content , application/json etc

No comments:

Post a Comment