##The operating environment of this tutorial: Windows 10 system, vue3 version, DELL G3 computerVue implements third-party requests: 1. Import axios through "import axios from 'axios';"; 2. Place axios on the prototype chain; 3. Add a request interceptor with code such as "axios .interceptors.request.use(config => {...}".
How does vue implement third-party requests?
Request third-party data in vue--axios
1 axios - > Based on Promise object-> async & await2 create phase-> Return Promise object-> The returned data can be directly deconstructed [Data processing]import axios from 'axios'; Vue.prototype.axios = axios;
axios.request(config)
axios.get(url[, config])
6 Interceptor
// 添加请求拦截器 axios.interceptors.request.use(config => { // 在发送请求之前做些什么 return config; }, error => { // 对请求错误做些什么 return Promise.reject(error); }); // 添加响应拦截器 axios.interceptors.response.use(response => { // 对响应数据做点什么 return response; }, error => { // 对响应错误做点什么 return Promise.reject(error); });
axios.interceptors.request.use(config => { // 在发送请求之前做些什么 let token = sessionStorage.getItem('userTk'); if (token) { config.headers.Authorization = token } return config }, error => { // 对请求错误做些什么 return Promise.reject(error); });
axios.interceptors.response.use(response => { if (response.data.code === '200') { Auth.setToken(sessionStorage.getItem('userId')) } return response; }, error => { console.warn(error); console.warn(error.response); if ((error.response.status && error.response.status === 401) || error.response.statusCode === 401) { // 已超时 Auth.removeToken(sessionStorage.getItem('userId')); sessionStorage.clear(); router.replace('/login') return Promise.reject('身份已过期,请重新登录!'); } if(error.response && error.response.status === 500) return Promise.reject('服务异常,请稍后重试!'); });
The above is the detailed content of How to implement third-party requests in vue. For more information, please follow other related articles on the PHP Chinese website!