Axios==_create请求实例

160 阅读1分钟

Axios 进行网络请求时,可以使用 axios.create() 方法创建一个自定义的 Axios 实例。这个自定义实例可以配置默认的请求选项,如基本URL、拦截器等,从而简化请求的重复性设置

使用 axios.create() 创建自定义 Axios 实例

  • 导入 Axios 模块并创建自定义实例:

import axios from 'axios';

const customAxios = axios.create();
  • 配置自定义实例的基本 URL:

const customAxios = axios.create({
  baseURL: 'https://api.example.com'
});
  • 配置自定义实例的请求拦截器:

customAxios.interceptors.request.use(
  config => {
    // 在请求被发送之前做一些处理
    return config;
  },
  error => {
    // 处理请求错误
    return Promise.reject(error);
  }
);
  • 配置自定义实例的响应拦截器:

customAxios.interceptors.response.use(
  response => {
    // 对响应数据做一些处理
    return response;
  },
  error => {
    // 处理响应错误
    return Promise.reject(error);
  }
);
  • 发送 GET 请求:

customAxios.get('/users')
  .then(response => {
    // 处理成功响应数据
  })
  .catch(error => {
    // 处理请求错误
  });
  • 发送 POST 请求:

const data = {
  username: 'example',
  password: 'password123'
};

customAxios.post('/login', data)
  .then(response => {
    // 处理成功响应数据
  })
  .catch(error => {
    // 处理请求错误
  });
  • 发送带有请求配置的请求:

const config = {
  params: {
    page: 1,
    limit: 10
  }
};

customAxios.get('/posts', config)
  .then(response => {
    // 处理成功响应数据
  })
  .catch(error => {
    // 处理请求错误
  });
  • 使用 async/await 发送请求:

async function fetchUserData() {
  try {
    const response = await customAxios.get('/user/123');
    // 处理成功响应数据
  } catch (error) {
    // 处理请求错误
  }
}

自定义 Axios 实例允许你在项目中重复使用相同的配置,同时可以对请求和响应进行全局处理。拦截器使你能够在请求发出之前和响应被处理之前执行一些操作。