【vue】axios + cookie + 跳转登录方法
axios 部分:
import axios from 'axios' import cookie from './cookie.js' // import constVal from './constVal.js' const axiosInstance = axios.create({ timeout: 1000 * 60 * 5 }) axiosInstance.interceptors.response.use(response => { // 接口数据返回之后response拦截 if (response.status !== 200) { let message = response.toString() || response.status + ':请求失败' return Promise.reject(message) } let rst = response.data if (rst && rst.xxx) { cookie.del('x.xxx.com', '/', 'xxx.com') location.href = rst.xxx + location.href } return response.data }, err => { return Promise.reject(err) }) export default { get (url, params, config) { const options = Object.assign({}, config, { method: 'get', url, params // timeout: 10000, }) return axiosInstance(options).then(response => { return response }).catch(error => { return Promise.reject(error) }) }, post (url, params, data, config) { const options = Object.assign({}, config, { method: 'post', url, params, data }) return axiosInstance(options).then(response => { return response }).catch(error => { return Promise.reject(error) }) }, put (url, params, data, config) { const options = Object.assign({}, config, { method: 'put', url, params, data }) return axiosInstance(options).then(response => { return response }).catch(error => { return Promise.reject(error) }) }, delete (url, params, data, config) { const options = Object.assign({}, config, { method: 'delete', url, params, data }) return axiosInstance(options).then(response => { return response }).catch(error => { return Promise.reject(error) }) }, all (...array) { return Promise.all(array).then(resList => { return resList }).catch(error => { return Promise.reject(error) }) } }
cookie 部分:
export default { get: function (name) { let r = new RegExp('(^|;|\\s+)' + name + '=([^;]*)(;|$)') let m = document.cookie.match(r) return (!m ? null : unescape(m[2])) }, add: function (name, v, path, expire, domain) { var s = name + '=' + escape(v) + '; path=' + (path || '/') + (domain ? ('; domain=' + domain) : '') // 默认根目录 if (expire > 0) { var d = new Date() d.setTime(d.getTime() + expire * 1000) s += ';expires=' + d.toGMTString() } document.cookie = s }, del: function (name, path, domain) { if (arguments.length === 2) { domain = path path = '/' } document.cookie = name + '=;path=' + path + ';' + (domain ? ('domain=' + domain + ';') : '') + 'expires=Thu, 01-Jan-70 00:00:01 GMT' } }
main.js 中引用:
import http from './utils/http.js' Vue.prototype.http = http // 使用方法为:this.http