import axios from "axios"; import { Message } from "element-ui"; import router from "../router/index"; const NODE_ENV = process.env.NODE_ENV; let http = axios.create({ baseURL: NODE_ENV === "development" ? "/api(开发环境)" : "正式环境后台地址", // 开发环境/正式环境(打包后) withCredentials: true, headers: { "Content-Type": "application/json", "Token": ‘‘ }, }); function apiAxios(method, url, params, response) { http({ method: method, url: url, data: method === "POST" || method === "PUT" ? params : null, params: method === "GET" || method === "DELETE" ? params : null, }).then(function (res) { response(res); }).catch(function (err) { response(err); }) } // 添加请求拦截器 http.interceptors.request.use(function (config) { const token = localStorage.getItem("token") || ""; config.headers[‘Token‘] = token; return config; }, function (error) { return Promise.reject(error); }); // 添加响应拦截器 http.interceptors.response.use(function (response) { return response; }, function (error) { if(error.response.data.message == "token信息失效") { Message({ showClose: true, message: "身份信息失效,请重新登录!", type: "warning" }); setTimeout(function(){
// 清除token 跳转登录页 localStorage.removeItem("token"); router.push({ path: "/" }) },2000); } return Promise.reject(error); });
export default { get: function (url, params, response) { return apiAxios("GET", url, params, response) }, post: function (url, params, response) { return apiAxios("POST", url, params, response) }, put: function (url, params, response) { return apiAxios("PUT", url, params, response) }, delete: function (url, params, response) { return apiAxios("DELETE", url, params, response) } }
// 请求示例
LoginBtn() { this.LoginIstrue = true; if(this.name == ‘‘){ this.$message({ showClose: true, message: ‘用户名不可为空!‘, type: ‘warning‘ });return false }else if(this.pwd == ‘‘) { this.$message({ showClose: true, message: ‘密码不可为空!‘, type: ‘warning‘ });return false } let url = ‘*****‘; let pwd = this.$md5(this.pwd); let params = { account: this.name, password: pwd, }; this.$axios.get(url, params, res => { if(res.data.code == 0) { localStorage.token = res.data.data; this.$router.push({ path: ‘/home‘ }) this.$message({ showClose: true, message: ‘欢迎您,管理员!‘, type: ‘success‘ }); this.LoginIstrue = false; }else{ this.$message({ showClose: true, message: res.data.message, type: ‘warning‘ }); this.LoginIstrue = false; } }); }
原文:https://www.cnblogs.com/zm-97/p/14201539.html