DrakaSAN DrakaSAN - 3 months ago 25
Node.js Question

Express, listen on multiples route

I am building a REST API based on express, I want to warn the user when he used the wrong HTTP verb for his request.

Currently, I am adding

app.all('/', (req, res) => {
answer(req, res, {code: 400, error: 'Wrong method'});
});


after each routes, and it is starting to be non negligeable, I d much rather have it at one place, and list all routes I want to listen to this.

Is there a way to do something like:

app.all(['/', '/signup', '/login'], (req, res) => {
answer(req, res, {code: 400, error: 'Wrong method'});
});


so that I only have one point of failure, instead of having to check every route?

Answer

Express uses path-to-regexp for matching the route paths; see the path-to-regexp documentation for all the possibilities in defining route paths. Express Route Tester is a handy tool for testing basic Express routes, although it does not support pattern matching.

You can use /^(signup|login)\/(.+)/. See DOCS

In your case:

app.all(['/^(signup|login)\/(.+)/'], (req, res) => {
    answer(req, res, {code: 400, error: 'Wrong method'});
});