节点 ExpressJS | 如何通过自定义查询参数验证

Nul*_*rue 6 javascript rest node.js express ecmascript-6

在这里学习 ExpressJS。我有get一条需要查询参数的路线,即


app.get('/api', (req, res) => {
  res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})

Run Code Online (Sandbox Code Playgroud)

在邮递员以下 http://localhost:5000/api?name=Messi&age=31&club=Barcelona

使用 res.body 返回 200 为:

{
    "name": "Messi",
    "age": "31",
    "club": "Barcelona"
}

Run Code Online (Sandbox Code Playgroud)

我如何编写自定义验证,其中:

  • 如果请求的查询参数不存在:状态 400
  • 如果缺少任何参数,即(姓名、年龄、俱乐部)返回响应,说明需要缺少的参数(姓名、年龄和/或年龄)

Nin*_*liu 6

上面的答案是正确的,但作为使用可扩展和可维护 API 的人,我建议使用JSON 模式来定义预期输入,并使用AJV来验证这些模式来标准化 API 的验证过程。

用法示例:

const Ajv = require('ajv');
const express = require('express');

const app = express();

app.get('/api', (req, res) => {

    // define precisely the expected shape of the request
    const schema = {
        type: 'object',
        properties: {
            name: { type: 'string' },
            age: { type: 'string' },
            club: { type: 'string' }
        },
        required: ['name', 'age', 'club']
    }

    // validate the request
    const ajv = new Ajv();
    const valid = ajv.validate(schema, req.query);
    if(!valid) res.status(400).send(ajv.errors);

    // request is valid. Do whatever
    res.send(req.query);

})

app.listen(8080, () => console.log('Server listening on port 8080'));
Run Code Online (Sandbox Code Playgroud)

响应/api

[
    {
        "keyword": "required",
        "dataPath": "",
        "schemaPath": "#/required",
        "params": {
            "missingProperty": "name"
        },
        "message": "should have required property 'name'"
    }
]
Run Code Online (Sandbox Code Playgroud)

响应/api?name=messi&age=10&club=barcelona

{
    "name": "messi",
    "age": "10",
    "club": "barcelona"
}
Run Code Online (Sandbox Code Playgroud)

是的,这需要更多的代码,但是请相信我,如果您想为复杂且可扩展的 API 验证准备应用程序,那么这就是您的最佳选择。


Mar*_*nde 4

您可以构建一个简单的验证中间件。

function validateQuery(fields) {

    return (req, res, next) => {

        for(const field of fields) {
            if(!req.query[field]) { // Field isn't present, end request
                return res
                    .status(400)
                    .send(`${field} is missing`);
            }
        }

        next(); // All fields are present, proceed

    };

}

app.get('/api', validateQuery(['name', 'age', 'club']), (req, res) => {
  // If it reaches here, you can be sure that all the fields are not empty.
  res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})
Run Code Online (Sandbox Code Playgroud)

您还可以使用第三方模块来验证请求。