VUE:axios(ベース版)をカプセル化し、リクエストタイムアウトなどを含む
3101 ワード
markdown , 。
axios, , 。
, , ( : ,504 ), ,
,
// axios , :https://www.npmjs.com/package/axios,axios ,
// params url , get , shinyway.com?key=params
// data (body) , post ,
import axios from 'axios'
import store from '@/store/index'
import qs from 'qs' // node.js , , ,
import router from '@/router' // , 404
import { getToken } from '@/utils/auth'
// axios axiso ,
const service = axios.create({
baseURL: process.env.BASE_API, // config/prod.env baseApi
timeout: 5000 //
})
//
service.interceptors.request.use(
config => {
// loadding
store.commit('CONTROL_LOADDING', true)
if (store.getters.token) {
config.headers['X-Token'] = getToken() // token--['X-Token'] key
}
// post ,
if (config.method === 'post' || config.method === 'put' || config.method === 'delete') {
config.data = qs.stringify(config.data)
}
return config
}, error => {
//
// alert(error.data.error.message)
return Promise.reject(error)
})
//
service.interceptors.response.use(res => {
//
// , loading
store.commit('CONTROL_LOADDING', false)
//
// 1.
if (res.data === '' || res.data.length === 0 || res.data === 'undefined' || res.data === undefined) {
console.log(' data / undefined')
}
// 2. ( , 。 , , , )
// if (res.data && !res.data.success) {
// console.log(res.data.error.message)
// }
return res.data
}, error => {
// ( 、 )
// loadding
store.commit('CONTROL_LOADDING', false)
console.log(error) // , error :message, config, code, request, response,
// 1.
if (error.code === 'ECONNABORTED' && error.message.indexOf('timeout') !== -1) {
console.log(' timeout/ , ')
// return service.request(originalRequest);//
}
// 2.
const errorInfo = error.response
console.log(errorInfo)
if (errorInfo) {
// error =errorInfo.data// catch , Promise.reject
if (errorInfo.status === 403) {
router.push({
path: '/error/403'
})
}
// if (errorInfo.status === 500) {
// router.push({
// path: "/error/500"
// });
// }
// if (errorInfo.status === 502) {
// router.push({
// path: "/error/502"
// });
// }
// if (errorInfo.status === 404) {
// router.push({
// path: "/error/404"
// });
// }
}
return Promise.reject(error) // (catch)
})
export default service