0
0
Expressframework~5 mins

JSON request and response patterns in Express

Choose your learning style9 modes available
Introduction

JSON is a simple way to send and receive data between a client and a server. Express helps handle JSON easily in web apps.

When building APIs that send data to web or mobile apps
When a client sends data like form inputs to the server
When you want to respond with structured data instead of HTML pages
When you need to exchange data between different systems in a simple format
Syntax
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.

Examples
This example receives user data in JSON and sends it back with a success status.
Express
app.use(express.json())

app.post('/user', (req, res) => {
  const user = req.body
  res.json({ status: 'success', user })
})
This example sends a JSON response with app info when a GET request is made.
Express
app.get('/info', (req, res) => {
  res.json({ app: 'MyApp', version: '1.0' })
})
Sample Program

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.

Express
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}`)
})
OutputSuccess
Important Notes

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.

Summary

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.