0

是否可以像这样在 ExpressJS 中制作路由器?

用户.js

const userController = ('../controllers/userController.js');

router.get('/:userName', userController.paramByUsername);
router.get('/:id', userController.paramByUserId);


在控制器中,代码看起来像这样

userController.js

function paramByUsername(req, res) {
    User.findOne({
        where: {
            userId: req.params.userId
        }
    })
    .then((user) => {
        if(!user) {
            return res.status(404).json({ message: "User not found."});
        }

        return res.status(200).json(user);
    })
    .catch((error) => {
        return res.status(400).json(error);
    });
}

function paramByUserId(req, res) {
    User.findByPk(req.params.id)
    .then((user) => {
        if(!user) {
            return res.status(404).json({ message: "User not found."});
        }
    }).catch((error) => {
        return res.status(400).json(error);
    });
}


通过上面的代码,我想要实现的是这样的端点:
/users/1这应该与/users/username.

我已经尝试了上面的代码,但是当我得到时我看到的是一个错误/users/:id

4

1 回答 1

1

你不能同时做这两个:

router.get('/:userName', userController.paramByUsername);
router.get('/:id', userController.paramByUserId);

从纯路由的角度来看,没有办法区分这两者。无论您先声明哪条路线,都会在顶层抓取所有内容,而第二条路线将永远不会被击中。

因此,在路线设计中,您必须确保根据您在路线模式中输入的内容,Express 路线匹配器可以唯一识别每条路线。

我想如果 anid总是只是数字而用户名永远不能只是数字,那么您可以使用正则表达式路由并仅匹配 id 的数字和用户名的所有其他内容,但这对我和我来说似乎有点脆弱d更喜欢更明确的东西。

我不知道您的应用程序的整体情况,但您可能想要这样做:

router.get('/user/:userName', userController.paramByUsername);
router.get('/id/:id', userController.paramByUserId);

或者,您可以使用带有如下 URL 的查询字符串:

/search?user=John
/search?id=4889

然后,您将只有一条路线:

router.get("/search", ....);

您将检查存在哪些属性req.query以确定您要查找的项目。

于 2020-01-07T05:05:48.610 回答