Last Updated: February 25, 2016
·
544
· davidgomes

Publishing an object as a JSON file with Node (express.js)

app.get('/result', function(req, res) {
  res.setHeader('Content-Type', 'application/json; charset=utf-8');
  res.end(JSON.stringify({ name: "David", age: 19 }, null, 4));
});

If you want to publish a JavaScript object as a JSON file (kind of like an API), all you have to do is the above. Read more on the JSON.stringify function.

This is really simple yet very useful.