Categories
Express JavaScript Answers

How to Return JSON Responses with Express?

Spread the love

To return JSON responses with Express, we can use the res.json method to return a JSON response.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000
app.set('json spaces', 2);

app.get('/', (req, res) => {
  const obj = { foo: 1, bar: 2, baz: 3 }
  res.json(obj)
})

app.listen(port, () => {
  console.log(`Example app listening at http://localhost:${port}`)
})

We call app.set to set the 'json spaces' setting to 2 to make the indentation of the JSON 2 spaces.

Then in the GET / route, we call res.json with an object to return the obj object as the response.

Therefore, the response we get is:

{
  "foo": 1,
  "bar": 2,
  "baz": 3
}

when we go to the GET / route.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published.