JSON is a simple way to send and receive data between a client and a server. Express helps handle JSON easily in web apps.
JSON request and response patterns in Express
app.use(express.json()) app.post('/path', (req, res) => { const data = req.body res.json({ message: 'Received', yourData: data }) })
Use express.json() middleware to parse incoming JSON requests automatically.
Use res.json() to send JSON responses easily.
app.use(express.json()) app.post('/user', (req, res) => { const user = req.body res.json({ status: 'success', user }) })
app.get('/info', (req, res) => { res.json({ app: 'MyApp', version: '1.0' }) })
This program creates a simple Express server that listens on port 3000. It uses JSON middleware to parse incoming JSON data. When a POST request is sent to /echo with JSON data, it responds by sending back a JSON object confirming receipt and showing the data.
import express from 'express' const app = express() const port = 3000 app.use(express.json()) app.post('/echo', (req, res) => { const receivedData = req.body res.json({ message: 'Data received', data: receivedData }) }) app.listen(port, () => { console.log(`Server running on http://localhost:${port}`) })
Always use express.json() before routes that expect JSON data.
Clients must set the Content-Type header to application/json when sending JSON.
Use res.json() instead of res.send() for automatic JSON formatting and headers.
Express makes handling JSON requests and responses simple with built-in middleware.
Use express.json() to parse incoming JSON data automatically.
Use res.json() to send JSON responses with correct headers.