How to get and validate requests with Express.js
I'll show you how to modify how Express.js handles requests. I'll also post the code on Git Hub for your reference.
overview
In Express.js, you handle requests inside middleware functions. A request object and a response object are passed as arguments to the middleware function. You use these objects to retrieve data related to requests, generate responses, and so on.
Here, I will explain how to process requests with Express.js using the following versions.
Express.js v4.17.1
nodejs v19.7.0
In addition, all the code created this time is posted on GitHub.
How to get request information
Use the request object to get information about the request. A request object stores information about a request from a client. Used within Express.js middleware functions to access data such as request headers, parameters, and body.
The sample code below is an example for understanding the request object in Express.js. Receive a GET request, access request headers, query parameters, and return a response containing those values.
request.js
const express = require('express');
const app = express();
app.get('/', (req, res) => {
// get request headers
const headers = req.headers;
// get query parameters
const queryParam = req.query.param;
const response = {
headers: headers,
queryParam: queryParam,
};
res.json(response);
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Commentary
- Create Express instance
const express = require('express');
const app = express();
Import an Express module and create an instance of it.
- Defining route handlers
app.get('/', (req, res) => {
// get request headers
const headers = req.headers;
// get query parameters
const queryParam = req.query.param;
const response = {
headers: headers,
queryParam: queryParam,
};
res.json(response);
});
Handles GET requests to the root (’/’). When a request comes in, get the request headers and query parameters and return an object containing them in JSON format as a response.
- Start server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Start the server with an instance of Express listening on port 3000. When the server starts, print the message “Server is running on port 3000” to the console.
test
curl http://localhost:3000
How to validate request information
Express.js allows you to validate requests using middleware functions.
This example validates that the name and age fields are required and age is numeric when a POST request is sent to the /users endpoint.
Install the joi package for validation.
npm install joi
validate.js
const express = require('express');
const Joi = require('joi');
const app = express();
app.use(express.json());
const schema = Joi.object({
name: Joi.string().required(),
age: Joi.number().required(),
});
app.post('/users', (req, res) => {
const { error } = schema.validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
const { name, age } = req.body;
// What to do if validation succeeds
res.send({ message: 'User created successfully', name, age });
});
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Commentary
- Import required modules
const express = require('express');
const Joi = require('joi');
Import Express and Joi (validation library).
- Creating an Express instance and configuring middleware
const app = express();
app.use(express.json());
Create an instance of Express and set the JSON body parser as middleware. This allows parsing the request body as JSON.
- Definition of validation schema
const schema = Joi.object({
name: Joi.string().required(),
age: Joi.number().required(),
});
Define your validation schema using Joi. This schema requires name
to be a required string and age
to be a required number.
- Defining route handlers
app.post('/users', (req, res) => {
const { error } = schema.validate(req.body);
if (error) return res.status(400).send(error.details[0].message);
const { name, age } = req.body;
// What to do if validation succeeds
res.send({ message: 'User created successfully', name, age });
});
Handles POST requests to /users
. It validates the request body against the schema and returns a 400 status code and error message if there is an error. If the validation succeeds, it will return a user creation success message and the user’s information as a response.
- Start server
app.listen(3000, () => {
console.log('Server is running on port 3000');
});
Start the server with an instance of Express listening on port 3000. When the server starts, print the message “Server is running on port 3000” to the console.
# test a successful request
curl -X POST -H "Content-Type: application/json" -d '{"name":"John", "age": 25}' http://localhost:3000/users
# test requests with validation errors
curl -X POST -H "Content-Type: application/json" -d '{"name":"John"}' http://localhost:3000/users
summary
Using the req
object allows you to:
- You can access request data such as request headers and query parameters.
- Get data for different parts of the request, such as request path parameters and body data.
- Obtain authentication and authorization information related to requests, such as authentication tokens and session information.
- Use middleware functions to validate and transform request data.
Using the req
object, you can perform various operations on the request data.
The req
object has many properties and methods that allow for a high degree of customization and control.