我是 Node js 编程新手,并尝试使用 Node js 开发 API,我能够从构建的 API 检索预期输出,但我想执行一些异常处理。为此,我想检查来自 URL 的请求参数是否不为空。下面是我的代码:
async function getDetails(input) {
// using knex to execute query
return queries.getbymultiwhere('table_name',{
name:input.name,
id:input.id,
role:input.role
})
}
router.get('/:name/:id/:role',(req,res)=>{
getDetails({
name:req.params.name,
id:req.params.id,
role:req.params.role}).then(Results=>{ Do something with results}
})
在上面的代码中,我想检查名称、ID 和 Angular 色参数值不为空。 任何有用的解决方案将不胜感激。
谢谢!
最佳答案
您可以创建一个中间件来检查这些参数。
function check(fields) {
return (req, res, next) => {
const fails = [];
for(const field of fields) {
if(!req.query[field]) {
fails.push(field);
}
}
if(fails.length > 0){
res.status(400).send(`${fails.join(',')} required`);
}else{
next();
}
};
}
app.get('/api', check(['name', 'id', 'role']), (req, res) => {
getDetails()...
});
关于javascript - 如何检查 Node js应用程序中请求url参数是否不为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59715194/