Install axios
npm install axios -s
Introduce axios and Element-UI Message prompt boxes
import axios from 'axios'
import Message from 'element-ui'
Copy the code
Axios configuration
const beseURL = ' '
if (process.env.NODE_ENV == 'development') {
baseURL = 'https://www.baidu.com'
} else if (process.env.NODE_ENV == 'debug') {
baseURL = 'https://www.ceshi.com'
} else if (process.env.NODE_ENV == 'production') {
baseURL = 'https://www.production.com'
}
axios.create({
timeout: 7000.// Request timeout
baseURL: beseURL,
headers: {
'Content-Type': 'application/json; charset=UTF-8',}})Copy the code
Axios interception before request
axios.interceptors.request.use((config) = > {
// Some wrapping logic before the request
// You can do something with the pre-request data, such as escape qs.stringify (), or you need to do some uniform formatting
return config
})
Copy the code
Axios requests response interception
axios.interceptors.response.use(
(response) = > {
// Request return processing, such as the status code 404 500 can do some encapsulation processing, according to their own needs
return response
},
(error) = > {
return error
}
)
Copy the code
Get request encapsulation
export function get(url, data = {}) {
return new Promise((resolve, reject) = > {
axios.get(url, data).then(
(response) = > {
if (response.data.code === 200) {
resolve(response.data.data)
} else {
Message.error(response.data.msg)
}
},
(err) = > {
reject(err)
let message = 'Request failed! Please check the network '
if (err.response) message = err.response.data.message
Message.error(message)
}
)
})
}
Copy the code
Post request encapsulation
export function post(url, data = {}) {
return new Promise((resolve, reject) = > {
axios.post(url, data).then(
(response) = > {
if (response.data.code === 200) {
resolve(response.data.data)
} else {
Message.error(response.data.msg)
}
},
(err) = > {
reject(err)
let message = 'Request failed! Please check the network '
if (err.response) message = err.response.data.message
Message.error(message)
}
)
})
}
Copy the code
Finally, the export
// You can mount it globally, or you can write an API file
export default {
post,
get,
}
Copy the code