在Electron中,localStorage仅在浏览器进程(渲染进程)中起作用, 这里axios请求需要使用electron-store来保存token。
安装electron-store
npm i electron-store -d
store.js
const Store = require("electron-store")
const app = require("electron").app
let option = {
//文件名称,默认 config
name: "config",
//文件后缀,默认json
fileExtension: "json",
//文件位置,尽量不要动,默认情况下,它将通过遵循系统约定来选择最佳位置。C:\Users\xxx\AppData\Roaming\test\config.json
cwd: app.getPath('userData'),
clearInvalidConfig: false, // 发生 SyntaxError 则清空配置,
}
const store = new Store(option);
export { store }
base.js
import axios from "axios";
import { store } from '@/utils/store';
const instance = axios.create({
baseURL: baseURL
});
instance.interceptors.request.use(config => {
if(store.get('token')){
config.headers['token'] = store.get('token');
}
return config;
})
instance.interceptors.response.use(async (result) => {
if (result.status && result.status == 200) {
if(result.data.code==0){
return {
status: result.status,
data: result.data
}
}
else if(result.data.code == "40302"){
//token 失效
let userInfo = store.get('userInfo');
const res = await getLoginUser({
loginName: userInfo.userName,
password: userInfo.password,
});
if (res.data.data && res.data.data.token) {
store.set('token', res.data.data.token);
store.set('userInfo', res.data.data);
// ... 更新其他数据
}
else {
return {
status: res.status,
data: res.data
}
}
}
else { //其他错误提示
return{
statusCode: 0,
errMsg: "【request】" + (result.data.info || result.data.msg),
data: result.data
};
}
}else {
return {
status: result.status,
errMsg: "【request】数据验证不通过",
data: result.data
}
}
})
export { instance }
login.vue
if (res.data.data && res.data.data.token) {
//登录成功
window.ipcApis.setStore({
key: 'token',
val: res.data.data.token
});
window.ipcApis.setStore({
key: 'userInfo',
val: res.data.data
});
//.....
} else {
Message.error('登录失败!' + res.data.msg);
}