Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to return a complex JSON response with Node.js?

Using nodejs and express, I'd like to return one or multiple objects (array) using JSON. In the code below I output one JSON object at a time. It works but this isn't exactly what I want. The response produced isn't a valid JSON response since I have many objects.

I am well aware that I could simply add all objects to an array and return that specific array in res.end. However I am afraid this could become heavy to process and memory intensive.

What is the proper way to acheive this with nodejs? Is query.each the right method to call?

app.get('/users/:email/messages/unread', function(req, res, next) {     var query = MessageInfo         .find({ $and: [ { 'email': req.params.email }, { 'hasBeenRead': false } ] });      res.writeHead(200, { 'Content-Type': 'application/json' });        query.each(function(err, msg) {         if (msg) {              res.write(JSON.stringify({ msgId: msg.fileName }));         } else {             res.end();         }     }); }); 
like image 772
Martin Avatar asked Jan 18 '12 05:01

Martin


People also ask

How do I return a response in JSON format in node JS?

stringify() to return JSON data): We will now use http. createServer() and JSON. stringify() to return JSON data from our server.

How do I return a JSON response?

To return JSON from the server, you must include the JSON data in the body of the HTTP response message and provide a "Content-Type: application/json" response header. The Content-Type response header allows the client to interpret the data in the response body correctly.

How do I send response back in node JS?

setHeader('Content-Type', 'text/html'); this line will set the format of response content o text/html. write() function method on response object can be used to send multiple lines of html code like below. res. write('<html>'); res.


2 Answers

On express 3 you can use directly res.json({foo:bar})

res.json({ msgId: msg.fileName }) 

See the documentation

like image 82
zobi8225 Avatar answered Oct 23 '22 01:10

zobi8225


I don't know if this is really any different, but rather than iterate over the query cursor, you could do something like this:

query.exec(function (err, results){   if (err) res.writeHead(500, err.message)   else if (!results.length) res.writeHead(404);   else {     res.writeHead(200, { 'Content-Type': 'application/json' });     res.write(JSON.stringify(results.map(function (msg){ return {msgId: msg.fileName}; })));   }   res.end(); }); 
like image 44
danmactough Avatar answered Oct 23 '22 01:10

danmactough