EGG.JS
Egg-JWT & Typescript指南

2 min read
#Egg.js建议hxd们可以快速食用一下全文先 趁热(逃
配置向
npm i egg-jwt --save
安装即可- 在
config/plugins.ts
中声明插件
import { EggPlugin } from 'egg';
const plugin: EggPlugin = {
jwt: {
enable: true,
package: 'egg-jwt',
},
};
export default plugin;
- 在
config/config.default.ts
中定义secret
加密字符串
import { EggAppConfig, EggAppInfo, PowerPartial } from 'egg';
export default (appInfo: EggAppInfo) => {
// ......
config.jwt = {
secret: 'welcome', // token混淆加密的字符串
};
// ......
};
- 最后在
router.ts
中当作中间件来食用即可
import { Application } from 'egg';
export default (app: Application) => {
const { controller, router, jwt } = app;
// 需要JWT的模块
router.get('/userInfo', jwt, controller.user.getUserInfo);
};
配置到这里就可以愉快的玩(cai)耍(keng)了 具体的可以直接去看官方文档👉egg-jwt
踩坑
一定要在typing/index.d.ts
定义成any
不然会在router
中报不符合中间件类型错误 过不了编译zzz
import 'egg';
declare module 'egg' {
interface Application {
jwt: any;
}
}
不定义any
的勇士还会发现一个坑 那就是迷惑的verify
方法的返回类型
// 官方定义的verify方法 返回的类型竟然是写死的string 然而实际使用发现返回的类型是object
/**
* call jsonwebtoken's verify() method
* @param token jwt token.
* @param secretOrPrivateKey secret key。string or { key, passphrase }
* @param options jwt options。see more details in https://github.com/auth0/node-jsonwebtoken
* @param callback callback
*/
verify(token: string, secretOrPrivateKey: string, options?: VerifyOptions, callback?: VerifyCallback): string;
Egg
对Typescript
真的越来越友好了呢(误😑