axios 学习笔记

2022-03-30  本文已影响0人  张_何

介绍

Axios 是一个基于 promise 的 HTTP 库,可以在浏览器和 node.js 中使用。

特性

安装

使用

axios函数

 axios({
      method: 'POST', // 请求类型
      url: 'http://localhost:3000/abc', // 请求 url
      data: {
          title: "今天天气不错, 还挺风和日丽的",
          author: "张三"
      } // 请求体
  }).then(response => {
      console.log(response);
  })

请求方法别名

axios.request({
    method:'GET',
    url: 'http://localhost:3000/abc'
}).then(response => {
    console.log(response);
})
axios.get('http://localhost:3000/abc' ).then(response => {
    console.log(response);
})
axios.post(
  'http://localhost:3000/abc', 
  {
    "body": "喜大普奔",
    "postId": 2
  }
).then(response => {
    console.log(response);
})

默认配置

axios.defaults.method = 'GET';//设置默认的请求类型为 GET
axios.defaults.baseURL = 'http://localhost:3000';//设置基础 URL
axios.defaults.params = {id:100};// 设置默认参数
axios.defaults.timeout = 3000;// 超时时间
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

设置默认参数后,我们再实现请求的时候就会变的简单

axios({// 这里请求不在设置请求方式,响应时间等,会使用默认设置的
    url: '/posts' // 这里我们只需求指定路径即可,会自动帮我们把 BaseUrl 加上
}).then(response => {
    console.log(response);
})

实例对象

const axios1 = axios.create({// 创建axios实例对象时,可以设置默认配置
    baseURL: 'https://abc.com',
    timeout: 5000
});
const axios2 = axios.create({
    baseURL: 'https://def.com',
    timeout: 2000
});

axios1.get('/getJoke').then(response => {
    console.log(response.data)
})

axios2({
    url: '/getJoke',
}).then(response => {
    console.log(response);
});

上面我们求创建了两个axios对象,axios1 和 axios2, 使用实例对象有什么好处呢? 我们使用axios默认配置的时候,默认配置只能配置一份, 但有时候,我们接口的 baseUrl,超时时间,请求方式的可能不一样,这样我们就可以分别创建多个不同的实例对象,将默认配置请求相同的归纳到一起。

// 使用由库提供的配置的默认值来创建实例
// 此时超时配置的默认值是 '0'
var instance = axios.create();
// 覆写库的超时默认值
// 现在,在超时前,所有请求都会等待 2.5 秒
instance.defaults.timeout = 2500;
// 为已知需要花费很长时间的请求覆写超时设置
instance.get('/longRequest',{
timeout:5000
})

拦截器

请求拦截器
axios.interceptors.request.use(function (config) {
      // 这个 config 就是我们发送请求配置的对象
      // 在这里我们可以修改 config 中的参数
      config.params = {a:100};
      return config;
  }, function (error) {
      return Promise.reject(error);
  });

axios.interceptors.request.use(function (config) {
    config.timeout = 2000;
    return config;
}, function (error) {
    return Promise.reject(error);
});

上面我们给请求设置了两个请求拦截器,它们是怎么调用的呢?

这里先调用的是后设置的请求拦截器,然后再调用先设置的请求拦截器

const instance = axios.create();
instance.interceptors.request.use(function(){...})</pre>

*   可以使用 axios.interceptors.request.eject 来移除拦截器

<pre>const myInterceptor = axios.interceptors.request.use(function(){...})
axios.interceptors.request.eject(myInterceptor);
响应拦截器
axios.interceptors.response.use(function (response) {
    // 这里的 response,就是接口响应的数据,包括响应行,响应头,响应体等,
    // 如果只需要响应体,可以直接返回 response.data
    return response.data;
    // return response;
}, function (error) {
    return Promise.reject(error);
});

axios.interceptors.response.use(function (response) {
    return response;
}, function (error) {
    return Promise.reject(error);
});

上面我们也设置了两个响应拦截器,其调用顺序又是怎么样的呢?

这里先调用的是先设置的响应拦截器,后调用后设置的响应拦截器

取消请求

//2.声明全局变量
let cancel = null;
//发送请求
function(){
  //检测上一次的请求是否已经完成
  if(cancel !== null){
      //取消上一次的请求, 例如刷新
      cancel();
  }
  axios({
      method: 'GET',
      url: 'http://localhost:3000/abc',
      //1\. 添加配置对象的属性
      cancelToken: new axios.CancelToken(function(c){
          //3\. 将 c 的值赋值给 cancel
          cancel = c;
      })
  }).then(response => {
      console.log(response);
      //将 cancel 的值初始化
      cancel = null;
  })
}
上一篇下一篇

猜你喜欢

热点阅读