Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wildcard in Express/node.js router

I would like to "get rid" of the router in node.js. Currently, what I have is something that looks like this:

app.get '/thing1', (req, res) ->
    res.render 'thing1'

app.get '/thing2', (req, res) ->
    res.render 'thing2'

Is there a way to collapse these to something like this:

app.get '/(*)', (req, res) ->
    res.render '(*)'

PS: I'm using coffeescript, but an answer in any language is OK

like image 378
Alexis Avatar asked Dec 13 '12 03:12

Alexis


People also ask

How do I create a wildcard route in Express?

Express allow you to use a wildcard within a route path using * . For example, the path defined below can be access using anything that follows the base URL (for example, if you wanted to build a “catch all” that caught routes not previously defined). app. get('/*',function(req,res) { req.

What is wildcards in routing?

A Wildcard route has a path consisting of two asterisks (**). It matches every URL, the router will select this route if it can't match a route earlier in the configuration. A Wildcard Route can navigate to a custom component or can redirect to an existing route.

What is Express router () in node JS?

js server. The express. Router() function is used to create a new router object. This function is used when you want to create a new router object in your program to handle requests. Multiple requests can be easily differentiated with the help of the Router() function in Express.

What is the difference between Express () and Express router ()?

The main difference is that express() is a top level function, which means it performs core functionality for the library and it contains its own methods where, as a matter of fact, Router is one, and that is why when we create a specific router we chain the Router() method on express , kind of like how we use app.


2 Answers

app.get('/:thing', function (req, res) {
  res.render(req.params.thing)
})
like image 175
Jonathan Ong Avatar answered Nov 04 '22 14:11

Jonathan Ong


From http://expressjs.com/api.html#app.VERB :

app.get(/^(.*)$/, function(req, res, next){
  res.send(req.params[0]);
});

Working gist: https://gist.github.com/elliotf/5826944

like image 38
Elliot Foster Avatar answered Nov 04 '22 14:11

Elliot Foster