- Create a request.js file and import axios
import axios from 'axios'
Copy the code
- Create an instance of Axios
const request = axios.create({
baseURL: xxx,
// baseURL: 'project base'
timeout: 5000 // Set a 5-second delay to close requests
})
Copy the code
- Set up the request interceptor
/ / request. Interceptors. Request. Use () / / request interceptor
request.interceptors.request.use(config= > {
config.headers.Authorization = `Bearer ${token}` // Set request headers to carry tokens
return config
}, error= > {
console.log(error) // Error printing occurred
return error
})
Copy the code
- Set up the response interceptor
/ / request. Interceptors. Response. Use () / / response interceptors
request.interceptors.response.use(config= > {
return config // Success returns directly
}, error= > {
if (error.response.status === 401) { // If an error occurs, check the error code. 401 indicates insufficient permission and token has expired
alert('Token request timed out! Please log in again! ')
// Perform operations, such as deleting expired user data from vuEX
router.push('/login') // Forcibly return to the login page
}
return error
})
Copy the code
- Export the axios instance
export default request
Copy the code