expressjsHow do I implement validation in an Express.js application?
Validation is an important part of any application, and Express.js makes it easy to implement. Here's an example of how to do it in an Express.js application:
const express = require('express')
const app = express()
app.use(express.json()) // This line is necessary
app.post('/user', (req, res) => {
const { name, age } = req.body
if (!name || !age) {
return res.status(400).json({ error: 'Name and age are required' })
}
res.json({ name, age })
})
The express.json()
line is necessary to parse the body of the request into a JavaScript object. Then, the code checks if the name
and age
fields are present in the request body, and if they're not, it returns an error response.
Code explanation
const express = require('express')
- importing the Express.js libraryconst app = express()
- creating an Express.js applicationapp.use(express.json())
- parsing the body of the request into a JavaScript objectif (!name || !age)
- checking if thename
andage
fields are present in the request bodyreturn res.status(400).json({ error: 'Name and age are required' })
- returning an error response if eithername
orage
is not presentres.json({ name, age })
- sending a response with thename
andage
fields if they are present in the request body
Helpful links
More of Expressjs
- How do I use Zod with Express.js?
- How can I use express-zip js to zip and download files?
- How can I use Express.js and Winston together to create a logging system?
- How can I use an ExpressJS webhook to receive data from an external source?
- How can I use Express.js to generate a zip response?
- How do I set up a YAML configuration file for a Node.js Express application?
- How can I use Express.js to develop a web application?
- How can I use Server-Sent Events (SSE) with Express.js?
- How can I use the x-forwarded-for header in Express.js?
- How do I download a zip file using Express.js?
See more codes...