vue integrates axios encapsulation request

王林
Release: 2023-05-24 09:54:07
Original
697 people have browsed it

Vue’s component-based development method makes our front-end development more flexible and efficient, and in this process, data interaction with the back-end is inevitable. Axios is a good data request framework. It provides a convenient API interface, is simple to use, reliable, and easy to expand, so we chose to integrate it into the Vue project. In this article, we will introduce how to encapsulate Axios into a practical request method for easy use in Vue components.

Introduction to Axios

Generally speaking, when we use Axios to send a request, the following three steps are involved:

  1. Create an Axios instance:
// axios实例的默认配置 const instance = axios.create({ baseURL: '', timeout: 5000, headers: { 'Content-Type': 'application/json' } });
Copy after login
  1. Send a request:
instance.get('/api/getUser', { params: { id: 123 } }).then(res => { console.log(res) }).catch(err => { console.log(err) })
Copy after login
  1. Respond to the request result:
instance.interceptors.response.use(res => { if (res.status === 200) { return res.data; } else { throw new Error(res.status); } }, err => { throw new Error(err); })
Copy after login

The use of Axios is very simple and clear, but if every time When used in Vue components, these codes must be written repeatedly, which is time-consuming and error-prone. Therefore, we can encapsulate it into a general request method:

Axios request encapsulation

We can use Promise, an asynchronous programming method, to encapsulate the Axios request into a general method and then unify it Process the returned results.

import axios from 'axios'; axios.defaults.baseURL = ''; axios.defaults.headers.post['Content-Type'] = 'application/json'; axios.defaults.timeout = 5000; // 请求拦截器 axios.interceptors.request.use( config => { // 将token添加到请求头中 if (localStorage.getItem('accessToken')) { config.headers.Authorization = localStorage.getItem('accessToken'); } return config; }, error => { return Promise.reject(error); } ); // 响应拦截器 axios.interceptors.response.use( response => { if (response.status === 200) { return Promise.resolve(response); } else { return Promise.reject(response); } }, error => { if (error.response.status) { switch (error.response.status) { case 401: // token过期,跳转到登录页 break; case 404: // 请求资源不存在 break; default: // 其他错误提示 break; } return Promise.reject(error.response); } } ) export default function request(options) { return new Promise((resolve, reject) => { axios(options).then(res => { resolve(res.data); }).catch(error => { reject(error); }) }) }
Copy after login

In the above code, we create an Axios instance and set its default configuration, and also add request and response interceptors. In the encapsulated request method, we use Promise to return the result of the request.

  • In the request interceptor, we can add Token to the request header, or we can also customize the request here.
  • In the response interceptor, we can perform special processing on the response results, such as jumps to status code errors, resource non-existence prompts, or other error prompts, etc.

Request method usage

After encapsulating the Axios request into a general method, we can use it in the Vue component. When calling, we only need to pass the basic parameters of the request:

import request from '@/utils/request'; export function fetchData() { return request({ url: '/api/list', method: 'get' }) }
Copy after login

Similarly, requests for HTTP methods such as GET, POST, PUT, DELETE, and PATCH are supported. Just specify different methods in the parameters.

request({ url: '/api/user', method: 'post', data: { username: 'admin', password: '123456' } }); request({ url: '/api/user', method: 'put', params: { id: 123 }, data: { username: 'admin', password: '123456' } }); request({ url: '/api/user', method: 'delete', params: { id: 123 } });
Copy after login

Conclusion

This article explains in detail how to encapsulate the Axios request method through the integration and encapsulation of Axios in the Vue project. This encapsulation method can greatly reduce the amount of repeated code writing, improve development efficiency, and also facilitate the unified processing of request results. During use, we can adjust and expand its configuration and interceptors as needed to meet different needs.

The above is the detailed content of vue integrates axios encapsulation request. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!