//下载 插件
npm install egg-jwt --save
// {app_root}/config/plugin.js 配置插件
exports.jwt = {
enable: true,
package: "egg-jwt"
};
// {app_root}/config/config.default.js 设置密钥
exports.jwt = {
secret: "123456" //自己设置的值
};
自己画的流程图:
react/src/views/login.jsx:
post('/login',{username,psw}).then(res => {
console.log(res) // 后端返回的token
window.localStorage.setItem('token',res)
})
egg / app / controller / login.js:
'use strict';
const Controller = require('egg').Controller;
class LoginController extends Controller {
async index() {
const { ctx } = this;
let {userName,psw} = ctx.request.body;
let result = await this.service.login.index(userName,psw) // 交给service处理生成 token
ctx.body = result;
}
}
module.exports = LoginController;
egg / app / service/ login.js:
module.exports = app => {
class LoginService extends app.Service {
async index(userName,psw) {
if(userName&&psw){
const token = app.jwt.sign({ userName,psw }, app.config.jwt.secret,{expiresIn:'24h'});
/*
* sign({根据什么生成token})
* app.config.jwt.secret 配置的密钥
* {expiresIn:'24h'} 过期时间
*/
return token
}
}
}
return LoginService
}
egg / app/ router.js:
router.get('/getData',jwt, controller.getData.index); // jwt 指明这个请求需要token才能收到返回结果
拦截器:
//拦截
request.interceptors.request.use((config) => {
config.headers.authorization = `Bearer ${window.localStorage.getItem("token")}`;
return config;
}, (err) => {
console.error(err);
});
//拦截响应
request.interceptors.response.use((response) => {
return response.data;
}, (err) => {
console.log(err);
});