I
I
Isaac Clark2014-07-12 16:34:01
Node.js
Isaac Clark, 2014-07-12 16:34:01

Node.js, Express: url handling, how to implement?

Hello, tell me please. Django handles urls nicely

urlpatterns = [
    url(r'^articles/2003/$', 'news.views.special_case_2003'),
    url(r'^articles/([0-9]{4})/$', 'news.views.year_archive'),
    url(r'^articles/([0-9]{4})/([0-9]{2})/$', 'news.views.month_archive'),
    url(r'^articles/([0-9]{4})/([0-9]{2})/([0-9]+)/$', 'news.views.article_detail'),
]

Is there such possibility in Node.js in Express or other framework. And how can this be done (article, example)? Thanks for your help and your time.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey Pavlov, 2014-07-12
@Dark_Knight

Have a look at this Express help section. It describes just that - how to set a controller for the url.
A few examples:
1) default index page handler:

app.get('/articles/2003/', function(req, res){
  res.send('articles in 2003 year');
});

2) Using Regex to validate url:
app.get(/^\/articles\/([0-9]{4})\/$/, function(req, res){
  res.send('articles in ' + req.params[0] + ' year');
});

3) Using format in url:
app.get('/user/:id', function(){
  // ... 
})

4) You can set the handler without specifying the inline function by placing the controllers in a separate file. So it will be even more like a subject:
var controllers = require('./controllers');
app.get('/articles/2003/', controllers.special_case_2003);
app.get(/^\/articles\/([0-9]{4})\/$/, controllers.year_archive);
app.get('/user/:id', controllers.user);

The controllers.js file describes the handler functions for each of the urls.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question