条件不返回错误(Express.js)

问题描述 投票:0回答:1

当我在 Postman 中使用 url“localhost:3000/api/users/id/”调用 GET 请求(不带 ID 号)时,当我使用以下地址调用 GET 请求时,我希望得到像这样的返回:查询为空:

{
    "errors": [
        {
            "type": "field",
            "msg": "Must not be empty",
            "path": "filter",
            "location": "body"
        }
}

但这就是我的回报:

<html lang="en">

<head>
    <meta charset="utf-8">
    <title>Error</title>
</head>

<body>
    <pre>Cannot GET /api/users/id/</pre>
</body>

这是代码:

app.get("/api/users/id/:id", findUserIndex, checkSchema(getUserValidationIdSchema), (req, res) => {

    const result = validationResult(req);
    const {userIndex} = req;

    if (!result.isEmpty()) return res.status(400).send({errors: result.array()});

    if (result.isEmpty()) return res.send(users[userIndex]);

})

这是函数 finderUserIndex:

const findUserIndex = (req, res, next) => {

    const {params: {id}} = req;
    const parsedId = parseInt(id);

    if (isNaN(parsedId)) return res.sendStatus(400);

    const userIndex = users.findIndex((user) => user.id === parsedId);

    if (userIndex === -1) return res.sendStatus(404);

    req.userIndex = userIndex;
    req.parsedId = parsedId;

    next();

}

这是模式获取 getUserValidationIdSchema:

export const getUserValidationIdSchema = {
    id: {
        notEmpty: {errorMessage: "Must not be empty"},
    }
}
javascript
1个回答
0
投票

Express 使用库,如下。正如您在部分链接中的包描述中看到的那样,它会告诉您可以使用“?”在路由参数的末尾以使其可选。 https://www.npmjs.com/package/path-to-regex#demonstration-of-processing-a-key-identifier-with-a-quantifier-

所以在你的情况下,路由字符串应该如下所示

"/api/users/id/:id?"
© www.soinside.com 2019 - 2024. All rights reserved.