javascript - 如何检查 Node js应用程序中请求url参数是否不为空?

标签 javascript node.js exception async-await

我是 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/

相关文章:

javascript - printToPDF 不会打印所有 webContent View

node.js - 在 Protractor 中为 e2e 测试设置 https 代理

c# - 无法识别在 C# 中使用对象初始值设定项时抛出异常的属性

javascript - 如何在 Angular 指令的 Jasmine 单元测试中触发点击事件?

javascript - 如何让用户能够添加另一个选择数据?

javascript - ng-react 比 ng-repeat 慢得多(不推荐访问属性 'nodeType' 错误)

python - 如何立即重新引发任何工作线程中抛出的异常?

javascript - NextJS 使用带有 URL 子路径的 getServerSideProps

node.js - 异步控制流-完全完成for循环后返回true

c++ - 如何使用 std::lock_guard 锁定对 std::map 的读写访问?