is it possible to name routes in Express.js

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

    Test
    

    Let you redirect to an url by name

    app.get('/test-redirect', function(req, res, next) {
        res.redirectToRoute('test', { x: 'world' });
    });
    

提交回复
热议问题