gpt4 book ai didi

javascript - 通过参数捕获错误的函数,我们将其作为参数

转载 作者:行者123 更新时间:2023-12-02 23:18:50 25 4
gpt4 key购买 nike

我需要为我的 Restful API 创建名为“access”的身份验证函数,并且每次用户想要与服务器交互时我希望它如下所示:

access(id , token ,function(err){
if(err){
res.send(err)
}else {
res.send('you have all permissions')
}
})

我如何编写这个函数以在每个身份验证步骤中使用?

最佳答案

对于身份验证,您通常需要一些中间件:

function isAuthenticated(req, res, next) {
// determine here if user is authenticated (and/or authorized)
if (user) {
next(); // user is authorized, call next
} else {
const error = new Error('unauthorized');
error.status = 400;
return next(err);
}
}

app.get('/authenticated/route', isAuthenticated, function(req, res) {
res.send('secret information');
});

我建议使用类似Passport.js的东西。它删除了许多身份验证中间件,特别是可以轻松地与 Google 和 Facebook 等提供商集成。

关于javascript - 通过参数捕获错误的函数,我们将其作为参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57037056/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com