Sometimes, we want to get HTTP method in controller with Express.js.
In this article, we’ll look at how to get HTTP method in controller with Express.js.
How to get HTTP method in controller with Express.js?
To get HTTP method in controller with Express.js, we can use the req.method
property.
For instance, we write
const register = (req, res) => {
if (req.method == "POST") {
//...
}
res.render('user/registration.html', {
form: form.toHTML()
});
}
app.get('/register', register)
app.post('/register', register)
to define the register
route handler function.
In it, we check the HTTP method used to make the request with req.method
.
Then we can use the same route handler function for routes with different methods.
Conclusion
To get HTTP method in controller with Express.js, we can use the req.method
property.