import axios from 'axios'
import qs from 'qs'
// Configure the environment
// let baseUrl = 'http://127.0.0.1:8080'
// let baseUrlArr = [
/ / {
// type: 'development',
/ / url: 'http://127.0.0.1:8080'
/ /},
/ / {
// type: 'test',
/ / url: 'http://127.0.0.1:8080'
/ /},
/ / {
// type: 'production',
/ / url: 'http://127.0.0.1:8080'
/ /}
// ]
switch (process.env.NODE_ENV) {
case 'production':
axios.defaults.baseURL = 'http://localhost:8080'
break
case 'test':
axios.defaults.baseURL = 'http://localhost:8080'
break
default:
axios.defaults.baseURL = 'http://localhost:8080'
}
// axios.defaults.baseURL = 'http://localhost:8080'
/ / axios.defaults.headers.com men [' Authorization '] = 'this is a Token'
// axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'
// Timeout and whether credentials and headers are allowed across domains
axios.defaults.timeout = 10000
axios.defaults.withCredentials = true
axios.defaults.headers['Content-Type'] = 'application/x-www-form-urlencoded'
// Request parameter passing
axios.defaults.transformRequest = data= > qs.stringify(data)// The method is the same as get plaintext, but has been encoded
// Interceptor, permission check token,vuex-> local storage, before sending a request
axios.interceptors.request.use(config= > {
/ / carry a token
let token = localStorage.getItem('token')
token && (config.headers.Authorization = token)
return config
}, error= > {
return Promise.reject(error)
})
// Response interceptor
axios.interceptors.response.use(respose= > {
// respose is an object that returns data, status, headers
return respose.data
}, error= > {
let {
response
} = error
if (response) {
// => The server at least returns a result
switch (response.status) { // Depending on the needs of the company, you can skip the page or pop the message
case 401: // => Permission to determine whether to log in
break
case 403: // => Token expires (common), request rejected
break
case 404: // => Cannot be found
break}}else {
// => The server does not even return the result
if (!window.navigator.onLine) {
// Break the page
return 0
}
return Promise.reject(error)
}
})
export default axios
Copy the code