表示默认路由参数 [英] Express default route parameter

查看:71
本文介绍了表示默认路由参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

令我惊讶的是我找不到它,所以它可能以前已经被回答过了(我正在寻找错误的东西).

I am surprised I can't find this so it has probably been answered before (and I'm searching for the wrong thing).

基本上可以吗,如何在nodejs Express路由上设置默认值?

Basically, is it possible and how do I set a default value on a nodejs express route?

// Test route
router.route('/tests/:id')
    .get(testsController.tests.get);

如果未设置:id,它将自动设置为任意值,例如1.

Where if :id is not set, it will automatically set to an arbitrary value, e.g. 1.

控制器代码:

var testsController = {
    tests: {
        get: function (req, res, next) {
            if (req.params.id) {
                res.render('tests.html', { title: 'The Site', id: req.params.id });
                next();
            } else {
                //res.redirect('/')
                console.log('here');
            }
        }
    }
};

我知道在PHP Symfony2中我可以做这样的事情:

I know in PHP Symfony2 I can do something like this:

/**
 * @Route("/tests/{id}")
 * @param Request $request
 * @return \Symfony\Component\HttpFoundation\Response
 */
public function testAction(Request $request, $id=1)
{
}

推荐答案

您已正确设置它,但之后需要从请求对象中获取参数,该参数不会自动传递给操作:

You are setting it up correctly, but you need to get the parameter afterwards from the request object, it is not passed automatically to the action:

req.params.id

要使参数成为可选参数,您应该按以下方式定义路由:

To make the parameter optional you should define the route like this:

router.route('/tests/:id?')
    .get(testsController.tests.get);

,如果要设置默认值,请执行以下操作:

and if you want to set a default value do that:

res.render('tests.html', { title: 'The Site', id: req.params.id || 1 });

这篇关于表示默认路由参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆