首页 > 解决方案 > 无法使用 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. 我只是想了解如何使用它。

标签: javascriptnode.jsexpress

解决方案


我个人没有使用过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)

推荐阅读