How to return JSON using Node.js and Express?

Sometimes, we want to return JSON using Node.js and Express.

In this article, we’ll look at how to return JSON using Node.js and Express.

How to return JSON using Node.js and Express?

To return JSON using Node.js and Express, we can use the res.end and res.json method.

For instance, if we use the http package, we write

const http = require('http');

const app = http.createServer((req, res) => {
  res.setHeader('Content-Type', 'application/json');
  res.end(JSON.stringify({
    a: 1
  }, null, 3));
});
app.listen(3000);

to call http.createServer to create the server.

Then we call res.end with the stringified JSON object as the response.

With Express, we call app.json with

res.json({ a: 1 });

to return the JSON response with the object.

Conclusion

To return JSON using Node.js and Express, we can use the res.end and res.json method.