Categories
Express JavaScript Answers

How to Set Response Status and JSON Content in a REST API Made with Node.js and Express?

Spread the love

To set response status and JSON content in a REST API made with Node.js and Express, we call the res.status method with the HTTP status code that we want to return.

For instance, we can write:

const express = require('express')
const app = express()
const port = 3000

app.get('/', (req, res) => {
  res.send('hello world');
});

app.get('/error', (req, res) => {
  res.status(500).send({ error: "error" });
});

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

We add the /error route, which returns a 500 response by call res.status with 500.

Then we call send with an object to return that as the JSON response body.

By John Au-Yeung

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

Leave a Reply

Your email address will not be published.