Home > Web Front-end > Vue.js > body text

How to encapsulate Vue3 Axios interceptor into request file

王林
Release: 2023-05-19 11:49:44
forward
1310 people have browsed it

1. Create a new file named request.js and import it into Axios:

import axios from 'axios';
Copy after login

2. Create a function named request and export it:

Create a The function is called request and is set to a new Axios instance with a base URL. To set a timeout in a wrapped Axios instance, pass the timeout option when creating the Axios instance.

export const request = axios.create({
  baseURL: 'https://example.com/api',
  timeout: 5000, // 超时设置为5秒
});
Copy after login

3. Add an interceptor in the request function:

request.interceptors.request.use(function (config) {
  // 在发送请求之前做些什么
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});

request.interceptors.response.use(function (response) {
  // 对响应数据做点什么
  return response;
}, function (error) {
  // 对响应错误做点什么
  return Promise.reject(error);
});
Copy after login

This will add a request interceptor and a response interceptor. You can perform required actions in these interceptors, such as adding authentication headers before the request is sent or checking the response data for errors after the response is returned.

4. Finally, export the request function:

export default request;
Copy after login

Now, every network request that passes the predefined interceptor can be executed through the request function in the application. For example:

import request from './request';

request.get('/users')
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
Copy after login

This will make a GET request using a wrapped Axios instance and then handle the response using a predefined interceptor

Full example:

To be carried before sending the request Token and Username, you can use a request interceptor to add authentication headers to all requests,

The request interceptor checks whether values ​​named "token" and "username" exist in localStorage and adds them as Authorization and Username headers. Adjust the names and values ​​of these headers as appropriate.

To operate on response data, use response interceptors. In the above example, the response interceptor will verify whether the "status" attribute in the response data is "success". If not, treat it as an error and throw it as an exception. The response object contains exception information, including all information such as response headers, status codes, and response bodies. The logic of these checks and exception throwing can be adjusted according to the actual situation.

import axios from 'axios';

export const request = axios.create({
  baseURL: 'https://example.com/api',
  timeout: 5000, // 超时设置为5秒
});

request.interceptors.request.use(function (config) {
  // 在发送请求之前添加身份验证标头
  config.headers.Authorization = `Bearer ${localStorage.getItem('token')}`;
  config.headers.Username = localStorage.getItem('username');
  return config;
}, function (error) {
  // 对请求错误做些什么
  return Promise.reject(error);
});
request.interceptors.response.use(function (response) {
  // 对响应数据做些什么
  const responseData = response.data;
  if (responseData.status !== 'success') {
    const error = new Error(responseData.message || '请求失败');
    error.response = response;
    throw error;
  }
  return responseData.data;
}, function (error) {
  // 对响应错误做些什么
  return Promise.reject(error);
});
Copy after login

The above is the detailed content of How to encapsulate Vue3 Axios interceptor into request file. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template