# Request
# Introduction
The request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on. In this documentation and by convention, the object is always referred to as req (and the HTTP response is res) but its actual name is determined by the parameters to the callback function in which you’re working.
Route.get("/", (req: Request, res: Response) => { res.status(200).send("Welcome to ExpressWebJs"); });
Copied!
The req object is an enhanced version of Node’s own request object and supports all built-in fields and methods.
# Query string and route params
Handling query parameters (query strings) is a common task when building APIs or web applications. Query parameters are usually passed in the URL after a ? and separated by &. ExpressWebJs provides an easy way to access and parse these query parameters. Here's how you can handle query strings in ExpressWebJs:
If you make a GET request to /api/users?name=Alex&age=10
, req.query will be { name: 'Alex', age: '10' }.
Route.get("/users", (req: Request, res: Response) => { const { name, age } = req.query; res.status(200).send(`Name: ${name}, Age: ${age}`); });
Copied!
If you make a GET request to /api/user/123
, req.params.id will be '123'.
Route.get("/user/:id", (req: Request, res: Response) => { res.status(200).send(req.params.id); });
Copied!
# Request body
You can retrieve the request body by utilizing the req.body
method.
Route.get("/", (req: Request, res: Response) => { req.body; });
Copied!
# req.originalUrl
The originalUrl method returns the request's path information which is the path of the request URL. So, if the incoming request is targeted at http://example.com/api/createBook, the path method will return createBook.
# req.baseUrl
The Url path on which a router instance was mounted.
# req.method
The method method will return the HTTP verb for the request. This can be a GET,POST,PUT DELETE and so on.
For more on request and response, visit expressjs.com (opens new window).