ExpressJs Handling HTTP Methods
Syntax
app.METHOD(PATH, HANDLER)
app
is an instance of the express module.METHOD
is an HTTP request method, such asGET
,POST
,PUT
,PATCH
,DELETE
.PATH
is the route path.HANDLER
is a callback function that executes when the route is matched.
Example
const express = require('express')
const app = express()
app.get('/', (req, res) => {
res.send('Hello World!')
})
app.post('/users', (req, res) => {
res.send('User created!')
})
app.put('/users/:id', (req, res) => {
res.send(`User with ID ${req.params.id} updated!`)
})
app.delete('/users/:id', (req, res) => {
res.send(`User with ID ${req.params.id} deleted!`)
})
app.listen(3000, () => {
console.log('Server started on port 3000')
})
Output
$ curl http://localhost:3000 # GET request
Hello World!
$ curl -X POST http://localhost:3000/users # POST request
User created!
$ curl -X PUT http://localhost:3000/users/1 # PUT request
User with ID 1 updated!
$ curl -X DELETE http://localhost:3000/users/1 # DELETE request
User with ID 1 deleted!
Explanation
app.get('/', ...)
registers a route handler for theGET
request method on the root path.app.post('/users', ...)
registers a route handler for thePOST
request method on the/users
path.app.put('/users/:id', ...)
registers a route handler for thePUT
request method on the/users/:id
path, where:id
is a dynamic parameter.app.delete('/users/:id', ...)
registers a route handler for theDELETE
request method on the/users/:id
path, where:id
is a dynamic parameter.
Use
HTTP methods are an essential part of building RESTful APIs with Express. By properly handling each method, you can build a secure and efficient API that allows your clients to interact with your server in a standardized way.
Examples of applications that use HTTP methods include social networks, online marketplaces, and e-commerce sites.
Important Points
- Express provides a simple and consistent API for handling HTTP methods.
- Routes can be matched based on a combination of the HTTP method and the path.
- Dynamic parameters can be used in route paths by prefixing them with a colon
:
character. - Route handlers take two parameters:
req
, which represents the incoming request, andres
, which represents the server's response.
Summary
In this tutorial, you learned how to use Express to handle HTTP methods. We covered the basic syntax for registering route handlers for different methods, and we provided an example of how to use these handlers to build a simple RESTful API. We also discussed some of the important points to keep in mind when working with HTTP methods, such as the use of dynamic parameters and the distinction between the request and response objects.