axiosoptions:从各个方面详细阐述

发布时间:2023-05-20

一、基础使用

axiosoptions 是对 axios 进行配置的一个对象,在每次向服务器发送请求时,axios 都会读取 axiosoptions 中对应的配置来设置请求参数和响应处理方式。 使用 axiosoptions 最基础的方法就是直接传入一个包含 urlmethod 等基本信息的对象来进行请求。代码示例如下:

axios({
  method: 'get',
  url: 'https://api.example.com',
})
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

上述示例中,我们传入了一个包含 urlmethod 的对象来进行 get 请求,axios 会自动将该对象转化为请求参数,对应的响应结果会通过 thencatch 进行处理。

二、配置请求参数

axiosoptions 中可以设置的请求参数除了最基础的 urlmethod 之外,还有以下参数:

  • headers: 设置请求头信息,可以是一个对象或函数
  • params: 以 key:value 的形式设置请求 url 中的查询参数
  • data: 设置请求体中的数据,仅在 postputpatch 方法中有效
  • timeout: 设置请求超时时间,单位是毫秒
  • auth: 设置身份验证信息
  • responseType: 设置响应数据的类型,可选值包括 arraybufferdocumentjsontextstreamblob
  • maxContentLength: 设置响应数据的最大长度,单位是字节
  • maxRedirects: 设置最大重定向次数 示例代码如下:
axios({
  url: 'https://api.example.com',
  method: 'post',
  headers: {
    'Content-Type': 'application/json',
  },
  params: {
    key1: 'value1',
    key2: 'value2',
  },
  data: {
    name: '张三',
    age: 20,
  },
  timeout: 5000,
  auth: {
    username: 'username',
    password: 'password',
  },
  responseType: 'json',
  maxContentLength: 1000000,
  maxRedirects: 5,
})
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

三、拦截器

axiosoptions 中,我们可以设置请求和响应的拦截器,分别对请求和响应进行处理。 一个请求拦截器的示例代码如下:

axios.interceptors.request.use(
  function (config) {
    // 在发送请求之前做些什么
    config.headers['Authorization'] = 'Bearer ' + getToken();
    return config;
  },
  function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  }
);

一个响应拦截器的示例代码如下:

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

拦截器可以对我们的请求和响应进行一些处理,例如在请求头加入授权信息、在响应数据中过滤掉不需要的数据等等。 需要注意的是,我们可以通过 axios.interceptors.request.eject()axios.interceptors.response.eject() 来删除拦截器。

四、创建实例

在使用 axios 进行多次请求时,我们可能需要对一些公共参数进行统一的配置。此时,可以使用 axios.create() 方法创建一个 axios 实例,在该实例上进行配置。 示例代码如下:

const instance = axios.create({
  baseURL: 'https://api.example.com/api',
  timeout: 5000,
  headers: {
    'Content-Type': 'application/json',
  },
});
instance.get('/user', {
  params: {
    id: 1,
  },
})
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
instance.post('/user', {
  name: '张三',
  age: 20,
})
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

在上述代码中,我们通过 axios.create() 创建了一个实例,该实例中包含了 baseURLtimeoutheaders 等配置。之后我们就可以通过该实例进行 getpost 请求,相当于在每个请求中都包含了上述的公共配置。

五、取消请求

axios 发送请求的过程中,有时候我们可能需要取消某个请求。axios 提供了 cancel token 的方式来实现请求的取消。 使用 cancel token 的示例代码如下:

// 创建一个取消令牌
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
// 发送请求
axios.get('/user', {
  cancelToken: source.token,
})
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    if (axios.isCancel(error)) {
      console.log('请求已被取消:' + error.message);
    } else {
      console.log(error);
    }
  });
// 取消请求
source.cancel('手动取消请求');

上述代码中,我们首先使用 CancelToken.source() 来创建一个取消令牌,将该取消令牌传入我们的请求配置中。之后,在需要取消请求的时候,我们可以通过 source.cancel() 方法来手动取消请求。

六、重试请求

axios 提供了重试机制来保证请求的可靠性。我们可以在 axiosoptions 中进行重试次数和重试间隔的配置。 示例代码如下:

axios({
  url: '/user',
  method: 'get',
  retry: 3,
  retryDelay: 1000,
})
  .then(function (response) {
    console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });

在上述代码中,我们将 retry 设置为 3,表示最多重试 3 次;将 retryDelay 设置为 1000,表示重试间隔为 1 秒。

七、总结

通过以上的阐述,我们了解了 axiosoptions 在使用 axios 进行请求时的各个方面。我们可以设置请求参数、请求和响应拦截器、创建实例、取消请求、重试请求等等。这些功能使得我们能够更好地处理接口调用过程中可能出现的各种情况,更加方便地进行开发。