在此处学习ExpressJS。
我有一条get
路由,该路由需要查询参数,即
app.get('/api', (req, res) => {
res.send({ name: req.query.name, age: req.query.age, club: req.query.club })
})
在邮递员上,以下http://localhost:5000/api?name=Messi&age=31&club=Barcelona
返回200,res.body为:
{
"name": "Messi",
"age": "31",
"club": "Barcelona"
}
问题
如何在以下位置编写自定义验证:
答案 0 :(得分:2)
您可以构建一个简单的验证中间件。
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 })
})
您还可以使用第三方模块来验证请求。
答案 1 :(得分:1)
您需要检查每个参数值
If(typeof req.query.name == 'undefined' )
{ res.status(400).send('name is missing') }
检查每个值
答案 2 :(得分:1)
以上答案是正确,但是作为使用过可扩展和可维护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验证准备应用程序,这就是方法。