DEV Community

Ibiyemi convenat
Ibiyemi convenat

Posted on

Express request types

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.

  1. req.params

Used to access route parameters from the URL.

Example: /user/:id

  1. req.query

Used to access query string parameters in the URL.

Example: /search?term=express

  1. req.body

Contains data sent in the request body (e.g., for POST or PUT requests).

Requires middleware like express.json()

  1. req.headers

Contains the headers sent by the client.

Access a specific header via req.headers['header-name'].

  1. req.method

The HTTP method of the request (e.g., GET, POST).

  1. req.url

The full URL path of the request.

  1. req.path

The path part of the URL.

  1. req.cookies

Contains cookies sent by the client

Example: Handling Requests

const express = require('express');
const app = express();

Middleware for Parsing Request Data

  1. Body Parsing:

JSON: app.use(express.json())

URL-encoded: app.use(express.urlencoded({ extended: true }))

  1. 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:

http://localhost:3000/login

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)