Friday 17 August 2012

Node js - set your content type if you are returning JSON objects



So I'm working on my app which at times return XHR json responses, and I was a little curious when the client interpreted the json as a string. Of course, stupid me forgot to set the content-type to be 'text/json' in the headers using Express. DUHHHH.

The correct way of doing it should be like this (note: `text/json`).

 app.post("/submitNew", function(req, res) {  

   var siteService = new site.SiteService();
   res.writeHead(200, {'Content-Type':'text/html'});
   var siteObj = req.body;
   if (siteService.isUnique(siteObj.url)) {
     siteService.save(siteObj, function(error, site) {
       rabbitmq.publish(site);
       res.write(JSON.stringify(site));
     });
   } else {
     res.write(JSON.stringify({error: true, field: 'url'}));
   }
   res.end('\n');
 });


No comments:

Post a Comment