Search code examples
jsonnode.jsexpressformatted

node and express send json formatted


I'm trying to send formatted json with express.

Here is my code:

var app = express();

app.get('/', function (req, res) {
  users.find({}).toArray(function(err, results){
    // I have try both
    res.send(JSON.stringify(results, null, 4));
    // OR
    res.json(results);
  });
});

I get the json in my browser but it's a string. How can I send it so it's readable in the browser?


Solution

  • You're going to have to set the Content-Type to application/json like this

    app.get('/', function (req, res) {
        users.find({}).toArray(function(err, results){
            res.header("Content-Type",'application/json');
            res.send(JSON.stringify(results, null, 4));
      });
    });