vue-cli的專案中關於axios的全域性配置
阿新 • • 發佈:2018-12-01
1. 使用easy-mock.com來模擬資料介面
2. npm install axios 安裝
3.新建目錄
其中的http.js 裡面是對axios請求介面的前期引數配置與後期資料的處理,直接上程式碼
import axios from 'axios'
const instance = axios.create({
headers: {
'content-type': 'application/json;charset=UTF-8',
'token': 'one'
},
baseURL: 'https://easy-mock.com/mock/5c01e1f6f221b94c907213d6/',
timeout: 10000,
withCredentials: true
})
// 新增請求攔截器
instance.interceptors.request.use(config => {
// 在傳送請求之前做某事,比如說 設定token
config.headers['token'] = 'token';
return config;
}, error => {
// 請求錯誤時做些事
return Promise.reject(error);
});
// 新增響應攔截器
instance.interceptors.response.use(response => {
// 對響應資料做些事
if (response.status === 200) {
console.log(response)
if (response.data && response.data.data.code === 1) {
console.log('成功')
response.data.data.value = '我是返回成功' // 在請求成功後可以對返回的資料進行處理,再返回到前臺
} else {
console.log('返回到登入...')
}
}
return response;
}, error => {
return Promise.reject(error.response.data); // 返回介面返回的錯誤資訊
})
export default instance;
index.js中就是對請求方法的簡單封裝,可以根據自己的需求來進行調整,程式碼如下
import axios from './http'
var depot = {}
depot.get = function ({ url, config = {}, cb }) {
axios.get(url, config).then((res) => {
if (res.status === 200) {
let result = res.data;
cb(result);
}
}).catch((error) => {
console.log('請求錯誤:' + error);
});
};
depot.post = function ({ url, data, cb }) {
axios.post(url, data).then(
(res) => {
if (res.status === 200) {
if (res.status === 200) {
let result = res.data;
cb(result);
}
}
}).catch((error) => {
console.log(error);
});
};
export default () => {
window.depot = depot;
};
4. 在main.js中進行配置
5. 頁面中的使用
depot.get({
url: 'demo/demo',
data: {},
cb: (res)=> {
console.log(res)
}
})
這樣一個簡單的axios的全域性封裝就弄好了