Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
729 views
in Technique[技术] by (71.8m points)

node.js - is it possible to name routes in Express.js

Basic route is like this:

app.get('/', function(req, res){
  res.send('hello world');
});

Is it possible to name that route and have it available in any template so it can be used like this:

app.get('/', name="index", function(req, res){
  res.send('hello world');
});

Go to site <a href="{% url index %}">index page</a>.

Inspiration comes from Django :)

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

There is no out of the box mechanism for that. However you can mimic Django's style like that: define urls.js file which will hold an array of URLs. First start with:

myviews.js

exports.Index = function( req, res, next ) {
    res.send( "hello world!" );
};

urls.js

var MyViews = require( "mywviews.js" );

module.exports = [
    { name : "index", pattern : "/", view : MyViews.Index }
]

Now in app.js ( or whatever the main file is ) you need to bind urls to Express. For example like this:

app.js

var urls = require( "urls.js" );

for ( var i = 0, l = urls.length; i < l; i++ ) {
    var url = urls[ i ];
    app.all( url.pattern, url.view );
};

Now you can define custom helper ( Express 3.0 style ):

var urls = require( "urls.js" ), l = urls.length;
app.locals.url = function( name ) {
    for ( var i = 0; i < l; i++ ) {
        var url = urls[ i ];
        if ( url.name === name ) {
            return url.pattern;
        }
    };
};

and you can easily use it in your template. Now the problem is that it does not give you fancy URL creation mechanism like in Django ( where you can pass additional parameters to url ). On the other hand you can modify url function and extend it. I don't want to go into all details here, but here's an example how to use regular expressions ( you should be able to combine these to ideas together ):

Express JS reverse URL route (Django style)

Note that I posted the question, so I had the same problem some time ago. :D


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...