javascript - 无法使用 express-unless 免除一些路由的身份验证
问题描述
我对 js 和 nodejs 还很陌生。所以,我尝试使用express-jwt来验证我的大部分 api。
但是,我想免除/login和/register等路由的身份验证
浏览了express-jwt的文档后,我了解到有一个名为express-unless的库
所以,我模仿了这个例子,看看我能不能让它工作。这是代码
const unless = require('express-unless');
app
.use(authenticateWithExpressJWT)
.unless({ path: ['/login'] });
authenticateWithExpressJWT是我的中间件功能,工作正常
const jwt = require('express-jwt');
const verifyJwt = jwt({ secret: 'secreyKey', algorithms: ['HS256'] });
module.exports.authenticateWithExpressJWT = verifyJwt;
当我在 Google 或 Stackoverflow 上搜索示例时,似乎其他人使用类似代码似乎没有任何问题。但是,当我这样做时,它甚至不会编译。我收到这个错误
app.use(authenticateWithExpressJWT).unless({ path: ['/login'] });
^
TypeError: app.use(...).unless is not a function
at Object.<anonymous> (/home/xyz/programming/node/firstApp/index.js:27:37)
at Module._compile (internal/modules/cjs/loader.js:778:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:789:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Function.Module.runMain (internal/modules/cjs/loader.js:831:12)
at startup (internal/bootstrap/node.js:283:19)
at bootstrapNodeJSCore (internal/bootstrap/node.js:623:3)
有人可以帮我弄清楚我做错了什么吗?
我还有一个问题:没有人怎么能使用unless()
方法require('express-unless');
?
const unless = require('express-unless');
无论我是否添加,我都会收到上述编译错误
注意:我知道我可以在不使用express-unless
. 我只是想了解如何使用它。
解决方案
我个人没有使用过express-unless
,但根据文档,你应该能够做到这一点,因为express-jwt
它本身支持 unless
:
const jwt = require('express-jwt');
const verifyJwt = jwt({ secret: 'secreyKey', algorithms: ['HS256'] })
.unless({path: ['/login'] });
module.exports.authenticateWithExpressJWT = verifyJwt;
然后在您的应用程序中使用您的中间件:
app.use(authenticateWithExpressJWT)
推荐阅读
- python - 模块对象在 pygame 中不可调用
- javascript - Firebase 错误:代码:“auth/user-not-found”
- typescript - TypeScript Fetch response.Json
- 预期 0 类型参数,但得到 1 - c# - 数据绑定时防止数据网格中的重复
- reactjs - 我在我的 jsfiddle 中收到错误未关闭的正则表达式
- android - 在片段中动态生成的 RadioGroup 中获取选中按钮
- redis - 无法加载密钥:redis 服务器不支持扫描命令
- reactjs - 带有 react/redux/router 流的搜索组件
- git - Jenkins 在构建之前无法清理工作区
- spring - 使用 Get 方法 @QueryParam 将枚举列表传递给 Spring REST