Home >Web Front-end >Vue.js >How to encapsulate Vue3 Axios interceptor into request file

How to encapsulate Vue3 Axios interceptor into request file

王林
王林forward
2023-05-19 11:49:441356browse

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

import axios from 'axios';

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秒
});

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);
});

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;

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);
  });

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);
});

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!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete