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

标签 javascript node.js express

我需要为我的 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/

相关文章:

node.js 服务器和 HTTP/2 (2.0) 与 express.js

javascript - 解释connect session中的length和clear session store方法

javascript forEach - 在所有按钮上添加 addEventListener

javascript - 错误 : Missing credentials in config -/nodeapp/node_modules/aws-sdk/lib/request. js:31

node.js - 排除虚拟字段

node.js - Mongoose - 根据 bool 属性对查找进行排序

javascript - Nodejs Socket 挂断和 ECONNRESET - 从 Meteor 到 Node js 服务器的 HTTP 发布请求

reactjs - 在 Fetch API 中设置授权 header

javascript - 使用 NodeJS 更新 JSON 对象中的值

javascript - jQuery append() 方法显示意外的非法 token 错误?