preface
In the VUE project, THE HTTP library of AXIOS is introduced for secondary encapsulation. This paper records the codes of secondary encapsulation based on the projects I have participated in.
Axios secondary encapsulation
import axios from 'axios' // Install axios
let url = "xxx" // The requested server URL
// Create an axios instance
const service = axios.create({
baseURL: url, / / the main path
withCredentials: true.// Allow cookies to be carried across domains
timeout: 5000 / / delay
})
// Set post and PUT to default content-type
service.defaults.headers.post['Content-Type'] = 'application/json'
service.defaults.headers.put['Content-Type'] = 'application/json'
/ / request
service.interceptors.request.use(config= > {
config.headers['X-Token'] = getToken('xxx')
// The getToken function is used to obtain the token
return config
},
error= > {
console.log(error) // A typo
return Promise.reject(error)
})
/ / reponse to intercept
service.interceptors.response.use(response= > {
const res = response.data
if(res.code ! = =200) {
Toast.fail(res.detail || res.msg)
// 50008: invalid token; 50012: Other customer login; 50014: Token expired;
if (res.code === 5008 || res.code === 50012 || res.code === 50014) {
Toast.fail('You have logged out, please log in again')
// todo
}
return Promise.reject(response)
} else {
if (response.detail) {
// todo
}
return res
}
},
(error) = > {
return Promise.reject(error)
})
export default service
Copy the code