Send a JSON response using Express Framework

Generally, we use res.send() method to send response to the API call. Here is the sample code.

const express = require('express);
const router = express.Router();
const app = express();

router.get('
/api', (req,res) => {
    res.send('
Hello World');
});

app.use('
/', router);
app.listen(3000);

You can send the JSON response by using res.json() method. It accepts an object and converts it into JSON before sending it as a response.

Example code:

const express = require('express);
const router = express.Router();
const app = express();

router.get('
/api', (req,res) => {
    res.json({ message: '
Hello World'});
});

app.use('
/', router);
app.listen(3000);

Looking for more Express framework tutorials? Learn from our DIY Express tutorials by building awesome apps.

Shahid
Shahid

Founder of Codeforgeek. Technologist. Published Author. Engineer. Content Creator. Teaching Everything I learn!

Articles: 299