How to get HTTP method in controller with Express.js?

Sometimes, we want to get HTTP method in controller with Express.js and JavaScript.

In this article, we’ll look at how to get HTTP method in controller with Express.js and JavaScript.

How to get HTTP method in controller with Express.js and JavaScript?

To get HTTP method in controller with Express.js and JavaScript, 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.