1.开发环境 vue+axios+typescript
2.电脑系统 windows10专业版
3.在开发的过程中,我们在做登录的时候会被要求使用token进行登录,下面我来分享一下使用方法(只是简单的封装),希望对你有所帮助。
4.在src目录下新建
4-1.chenhttp.js代码如下:
import axios from 'axios'
import qs from "qs"
// 环境的切换
if (process.env.NODE_ENV === 'development') {
// axios.defaults.baseURL = '/api';
axios.defaults.baseURL = '/api';
} else if (process.env.NODE_ENV === 'debug') {
axios.defaults.baseURL = ''
} else if (process.env.NODE_ENV === 'production') {
axios.defaults.baseURL = ''
}
axios.defaults.timeout = 10000;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8;multipart/form-data';
// 添加请求拦截器,在请求头中加token
axios.interceptors.request.use(
config => {
if (localStorage.getItem('Cusertoken')) {
config.headers.Ctoken = localStorage.getItem('Cusertoken');
}
return config;
},
error => {
return Promise.reject(error);
});
// 封装axios的post请求
const post = (url, params) => {
return new Promise((resolve, reject) => {
axios
.post(url, qs.stringify(params))
.then(response => {
resolve(response.data);
})
.catch(error => {
reject(error);
});
});
};
// 封装axios的put请求
const put = (url, params) => {
return new Promise((resolve, reject) => {
axios
.put(url, params)
.then(response => {
resolve(response.data);
})
.catch(error => {
reject(error);
});
});
};
// 封装axios的delete请求
const del = (url, params) => {
return new Promise((resolve, reject) => {
axios
.delete(url, params)
.then(response => {
resolve(response.data);
})
.catch(error => {
reject(error);
});
});
};
const get = (url, query) => {
return axios.get(url, query);
};
const $axios = {
post: post,
get: get,
put: put,
delete: del
};
export default $axios;
4-2.chenapi.js统一接口管理,小伙伴们根据自己的需求进行修改,代码如下:
import $axios from '@/chenhttp/chenhttp'
// chenl 是传的参数
export function login(chenl){
return $axios.post('/login',chenl);
}
5.在store文件夹下index.js(就是vuex)中添加如下代码:
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
export default new Vuex.Store({
state: {
usertoken:localStorage.getItem("Cusertoken")?localStorage.getItem("Cusertoken"):"",
},
mutations: {
changeLogin(state,user){
state.usertoken=user;
localStorage.setItem("Cusertoken",user);
}
},
actions: {
},
modules: {
}
})
6.在router.js中添加如下代码:
router.beforeEach((to, from, next) => {
// 如果用户访问的是登录页面 直接放行
if (to.path === '/login') return next();
// 从localStorage中得到token
const token = localStorage.getItem('Cusertoken');
// 如果没有token值 那么就跳转到'/login
if (!token) return next('/login');
// 如果有token则放行
next();
})
7.在login.js中添加如下代码:
import {login} from '@/chenhttp/chenapi';
login(){
enum Cobj{
nn="90",
}
login(Cobj).then(res=>{
console.log(res);
console.log(res.CHtoken);
(this as any).LoginObj.usertoken=res.CHtoken;
(this as any).$store.commit("changeLogin",res.CHtoken);
(this as any).$router.push('/index');
})
}
效果如下:
8.本期的分享到了这里结束啦(只是简单的封装,后期还会更新),希望对你有所帮助,让我们一起努力走向巅峰。