![]() |
VOOZH | about |
In Express.js, HTTP methods determine how a server handles client requests. They define the type of operation to perform on a resource, such as retrieving, creating, updating, or deleting data. Express allows defining routes that handle requests efficiently and in an organized manner.
Here are the different types of http requests
The GET method is an HTTP request used by a client to retrieve data from the server. It takes two parameters: the URL to listen on and a callback function with req (client request) and res (server response) as arguments.
Syntax:
app.get("URL",(req,res)=>{})In the above syntax
The POST method sends data from the client to the server, usually to store it in a database. It takes two parameters: the URL to listen on and a callback function with req (client request) and res (server response). The data sent is available in the request body and must be parsed as JSON.
Syntax:
app.post("URL",(req,res)=>{})In the above syntax
The PUT method updates existing data in the database. It takes two parameters: the URL to listen on and a callback function with req (client request containing updated data in the body) and res (server response).
Syntax:
app.put("URL",(req,res)=>{})In the above syntax:
The DELETE method removes data from the database. It takes two parameters: the URL to listen on and a callback function with req (containing the ID of the item to delete in the body) and res (server response).
Syntax:
app.delete("URL",(req,res)=>{})In the above syntax
The PATCH method is used to partially update data on the server. It takes two parameters: the URL to listen on and a callback function with req (containing the data to update, usually in the body or URL parameters) and res (server response).
Syntax:
app.patch("URL", (req, res) => {})In the above syntax:
Example: Implementation of above HTTP methods.
Output:
Express provides multiple ways to respond to requests. Besides res.send() and res.json(), you can use:
Method | Description |
|---|---|
res.download() | Prompt a file download. |
res.redirect() | Redirect the client to a different URL. |
res.render() | Render a view template. |
res.sendFile() | Send a file as an octet stream. |
res.sendStatus() | Set status code and send its string as response. |
res.end() | End the response process manually. |
res.json() | Send a JSON response. |
res.jsonp() | Send JSON with JSONP support. |