
How to send Json response in express js
Usually, API calls or request are handled by sending a response using res.send(…). You can equally send a json response using the in-built res.json() method.
This method accepts an object and converts it to json during response.
read also: morgan http request logger
Code example:
Below is a simple express app with one route running on port 3000.
The home route sends a json response.
const express = require('express');
const app = express();
const data = { name: 'john', age: 23, city: 'Douala', email: 'test@test.com' }
app.get('/', (req, res) => {
res.json(data) // Object can also be passed in the brackets directly
})
app.listen(3000, () => {
console.log('code running on port 3000');
})
Output:

Thanks for coding with me..?
Hope you learnt something new. You can always drop your comments and share with other devs. Remember we will cover more real code and projects in the next tutorials.
Links: Express Website, JSON
Leave a Comment