is it possible to name routes in Express.js

前端 未结 6 936
-上瘾入骨i
-上瘾入骨i 2020-12-15 23:58

Basic route is like this:

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

Is it possible to name that route and have it

相关标签:
6条回答
  • 2020-12-16 00:28

    I had the same problem and decided to make a library to help me out.

    Besides not hardcoding your routes, it allows me to build navigation components like breadcrumbs and I can use it server side with express or client side with Backbone or whatever.

    https://github.com/hrajchert/express-shared-routes

    0 讨论(0)
  • 2020-12-16 00:37

    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

    0 讨论(0)
  • 2020-12-16 00:39

    Another option that I don't see here is to just extract the route function out with a function name. If all you are trying to do is writing self-documenting code.

    function updateToDo(req, res, next) { /*do router stuff*/};
    router.put('/', updateToDo);
    
    0 讨论(0)
  • 2020-12-16 00:48

    I thing this is what you are looking for: Named routes

    Example code:

    var express = require('express');
    var app = express();
    
    var Router = require('named-routes');
    var router = new Router();
    router.extendExpress(app);
    router.registerAppHelpers(app);
    
    app.get('/admin/user/:id', 'admin.user.edit', function(req, res, next){
        // for POST, PUT, DELETE, etc. replace 'get' with 'post', 'put', 'delete', etc.
    
        //... implementation
    
        // the names can also be accessed here:
        var url = app.namedRoutes.build('admin.user.edit', {id: 2}); // /admin/user/2
    
        // the name of the current route can be found at req.route.name
    });
    
    app.listen(3000);
    

    As you can see you can name the route as admin.user.edit and access it in you views

    0 讨论(0)
  • 2020-12-16 00:51

    Check this Gist please

    var env="http://localhost:3000/"
    var route='users/:id/profile/'
    var routes=[
      {
        'name':'profile',
        'path':'users/:id/:profile/'
    
      }
    ]
    
    
    function RouteName(route,arg){
      let targetRoute = routes.find(e=>e.name==route).path
      for(var key in arg){
    
      targetRoute=targetRoute.replace(`:${key}`,arg[key])
      //console.log(targetRoute)
    
    }
    return targetRoute
    
    }
    
    console.log(env+RouteName('profile',{'id':3,'profile':'loaiabdalslam'}))
    
    0 讨论(0)
  • 2020-12-16 00:52

    I found express-reverse to nicely solve this issue

    https://github.com/dizlexik/express-reverse

    It augments the standard routing allowing you to pass the route's name as first argument

    app.get('test', '/hello/:x', function(req, res, next) {
        res.end('hello ' + req.params.x);
    });
    

    Let you build the url from inside a template by name

    <a href="<%= url('test', { x: 'world' }) %>">Test</a>
    

    Let you redirect to an url by name

    app.get('/test-redirect', function(req, res, next) {
        res.redirectToRoute('test', { x: 'world' });
    });
    
    0 讨论(0)
提交回复
热议问题