import axios from 'axios' import { Message } from 'element-ui' import store from '@/store/store' import qs from "qs" import { getToken } from '@/utils/auth' import {commonParams} from '@/api/config' import router from '@/router/index.js' let cancel ,promiseArr = {} const CancelToken = axios.CancelToken; // 建立axios默認請求 const service = axios.create({ baseURL: "http://localhost:8000/bpm/", timeout: 5000, // request timeout, }) // 請求攔截 service.interceptors.request.use(config => { // 爲了防止重複請求ajax if (promiseArr[config.url]) { promiseArr[config.url]('操做取消') promiseArr[config.url] = cancel } else { promiseArr[config.url] = cancel } // 拼接公共參數 config.params = Object.assign({},commonParams,config.params) //當爲傳統接收方式post的時候對參數進行序列化 if ( config.method === "put" || config.method === "delete" ) { // 序列化 config.headers = { 'Content-Type': "application/x-www-form-urlencoded;charset=utf-8" //當post的時候請求頭須要序列化 }; config.data = qs.stringify(config.data); } // 是否攜帶cookie不知 if (store.getters.token) { config.headers['Token'] = getToken() // 讓每一個請求攜帶token-- ['Token']爲自定義key 請根據實際狀況自行修改 } return config }, error => { // Do something with request error console.log(error) // for debug Promise.reject(error) }) // 相應攔截 service.interceptors.response.use( response => response, error => { if (error) { switch (error.response.status) { case 401: // router.push({ // path: "/login" // }); error.response.statusText = '未受權,請從新登陸' break; case 404: error.response.statusText = '請求錯誤,未找到該資源' Message({ // 餓了麼的消息彈窗組件,相似toast showClose: true, message: error.response.statusText, type: "error", center: true }); break; } } else { error.response.statusText = "鏈接到服務器失敗" } return Promise.reject(error) }) export default { //get請求 get (url,param) { return new Promise((resolve,reject) => { service({ method: 'get', url, params: param, // 取消請求函數建立 cancelToken: new CancelToken(c => { cancel = c }) }).then(res => { resolve(res) }).catch(error=>{ reject(error) }) }) }, //post請求 post (url,param) { return new Promise((resolve,reject) => { service.post( url, param, // 取消請求函數建立 { cancelToken: new CancelToken(c => { cancel = c }) } ).then(res => { resolve(res) }).catch(error=>{ reject(error) }) }) } }
帶序列化的請求 javascript