is it possible to name routes in Express.js

前端 未结 6 946
-上瘾入骨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: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

提交回复
热议问题