在这里学习 ExpressJS。
我有一个 get
路由需要查询参数,即
app.get('/api', (req, res) => {
res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})
在 postman 下面 http://localhost:5000/api?name=Messi&age=31&club=Barcelona
返回 200 和 res.body 为:
{
"name": "Messi",
"age": "31",
"club": "Barcelona"
}
问题
如何在以下位置编写自定义验证:
- 如果请求的查询参数不存在:status 400
- 如果缺少任何参数,即(姓名、年龄、俱乐部),则返回一个响应,说明需要哪个缺少的参数(姓名、年龄和/或年龄)
最佳答案
以上答案正确,但作为使用可扩展和可维护 API 的人,我建议使用 JSON Schemas 标准化您的 API 验证过程。定义预期的输入,以及 AJV验证这些模式。
示例用法:
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'));
响应/api
:
[
{
"keyword": "required",
"dataPath": "",
"schemaPath": "#/required",
"params": {
"missingProperty": "name"
},
"message": "should have required property 'name'"
}
]
响应/api?name=messi&age=10&club=barcelona
:
{
"name": "messi",
"age": "10",
"club": "barcelona"
}
是的,它需要更多的代码,但请相信我,如果您想要为复杂且可扩展的 API 验证准备您的应用程序,这是必经之路。
关于javascript - Node ExpressJS |如何通过自定义查询参数验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55049303/