启用CSRF令牌时AdonisJS出现Cannot read properties of undefined错误
解决AdonisJS开启CSRF后出现"Cannot read properties of undefined (reading 'get')"错误
这个错误的核心原因是Shield的CSRF功能依赖Session中间件,但Session中间件未在Shield之前注册,导致Shield无法访问Session对象的get方法。以下是具体解决步骤:
1. 注册Session中间件到全局中间件栈
修改start/kernel.ts,将Session中间件添加到Shield中间件之前:
Server.middleware.register([ () => import("@ioc:Adonis/Core/BodyParser"), () => import("@ioc:Adonis/Core/Session"), // 必须放在Shield之前 () => import("@ioc:Adonis/Addons/Shield"), ]);
2. 确认Session配置有效性
检查config/session.ts文件,确保驱动配置正确(比如使用cookie或file驱动),示例配置如下:
import sessionConfig from '@adonisjs/session/build/config' import Env from '@ioc:Adonis/Core/Env' export default sessionConfig({ driver: Env.get('SESSION_DRIVER', 'cookie'), cookieName: 'adonis-session', clearWithBrowser: false, age: '2h', cookie: { path: '/', httpOnly: true, secure: Env.get('NODE_ENV') === 'production', sameSite: false, }, })
3. 针对REST API的特殊处理
如果你的项目是纯REST API(比如使用JWT认证的无状态请求),可以根据需求调整:
- 跳过API路由的CSRF验证:在
config/shield.ts中添加例外路由:csrf: { enabled: true, exceptRoutes: [ '/api/**', // 匹配所有API路由,根据实际路由调整 ], enableXsrfCookie: true, methods: ['POST', 'PUT', 'PATCH', 'DELETE'], } - 禁用CSRF:纯无状态API不需要CSRF保护,保持
enabled: false即可,这也是最适合API场景的方案。
内容的提问来源于stack exchange,提问作者Reza Hashemi
相关产品推荐
相关产品推荐

