In Express.js, a request refers to the HTTP request made by the client to the server. Express provides a request object that contains all the details about the incoming request, such as headers, query parameters, body data, and more.
- req.params
Used to access route parameters from the URL.
Example: /user/:id
- req.query
Used to access query string parameters in the URL.
Example: /search?term=express
- req.body
Contains data sent in the request body (e.g., for POST or PUT requests).
Requires middleware like express.json()
- req.headers
Contains the headers sent by the client.
Access a specific header via req.headers['header-name'].
- req.method
The HTTP method of the request (e.g., GET, POST).
- req.url
The full URL path of the request.
- req.path
The path part of the URL.
- req.cookies
Contains cookies sent by the client
Example: Handling Requests
const express = require('express');
const app = express();
Middleware for Parsing Request Data
- Body Parsing:
JSON: app.use(express.json())
URL-encoded: app.use(express.urlencoded({ extended: true }))
- Cookies:
Install and use cookie-parser middleware:
const cookieParser = require('cookie-parser');
app.use(cookieParser());
Testing Requests
Use tools like Postman to test different types of requests. For example:
GET Request:
http//:Localhost/dashboard
POST Request:
All this request object that contains all the details above such as headers****, query parameters, body data are all request to get a object from a server
Top comments (0)