美文网首页
axios 学习笔记

axios 学习笔记

作者: 张_何 | 来源:发表于2022-03-30 20:34 被阅读0次

介绍

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

特性

  • 从浏览器中创建 XMLHttpRequests
  • 从 node.js 创建 http 请求
  • 支持 Promise API
  • 拦截请求和响应
  • 转换请求数据和响应数据
  • 取消请求
  • 自动转换 JSON 数据
  • 客户端支持防御 XSRF

安装

  • 终端执行:
    npm install axios

使用

axios函数

  • axios 提供了一个axios函数,可以直接通过这个函数发送请求,这个函数接收一个配置对象,我们可以在这个对象里设置请求类型(GET,POST,PUT,delete等),请求的 url,请求体等
 axios({
      method: 'POST', // 请求类型
      url: 'http://localhost:3000/abc', // 请求 url
      data: {
          title: "今天天气不错, 还挺风和日丽的",
          author: "张三"
      } // 请求体
  }).then(response => {
      console.log(response);
  })

请求方法别名

  • 为了方便,axios 为所有支持的请求方法提供了别名, 在使用别名方法时,url,method,data 这些属性都不必在配置中指定.
  • axios.request(config)
axios.request({
    method:'GET',
    url: 'http://localhost:3000/abc'
}).then(response => {
    console.log(response);
})
  • axios.get(url[, config])
axios.get('http://localhost:3000/abc' ).then(response => {
    console.log(response);
})
  • axios.post(url[, data[, config]])
axios.post(
  'http://localhost:3000/abc', 
  {
    "body": "喜大普奔",
    "postId": 2
  }
).then(response => {
    console.log(response);
})
  • axios.delete(url[, config])
  • axios.head(url[, config])
  • axios.options(url[, config])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])

默认配置

  • axios 给我们提供了默认配置的 api,通过默认配置 api,我们可以设置基础 url、默认请求方式、默认参数、超时时间、请求头参数等等,设置的这些默认配置将会被用在各个请求中。
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);
})

实例对象

  • axios 提供了使用实例对象的方式发送请求
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,超时时间,请求方式的可能不一样,这样我们就可以分别创建多个不同的实例对象,将默认配置请求相同的归纳到一起。

  • 配置的优先顺序: 所有的配置会以一个优先顺序进行合并,这个顺序是:在 lib/defaults.js 找到的库的默认值,然后是实例的 defaults 属性,最后是请求的 config 参数。后者将优先于前者
// 使用由库提供的配置的默认值来创建实例
// 此时超时配置的默认值是 '0'
var instance = axios.create();
// 覆写库的超时默认值
// 现在,在超时前,所有请求都会等待 2.5 秒
instance.defaults.timeout = 2500;
// 为已知需要花费很长时间的请求覆写超时设置
instance.get('/longRequest',{
timeout:5000
})

拦截器

  • axios 拦截器分为两种, 一种是请求拦截器,一种是响应拦截器
  • 设置后,在请求或响应被 then 或catch 处理前拦截它们
  • 我们需要在请求发出前设置好拦截器
请求拦截器
  • 使用axios.interceptors.request.use设置请求拦截器
  • 请求拦截器可以设置多个
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);
});

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

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

  • 同样也可以是自定义的axios 对象添加拦截器
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设置响应拦截器
  • 响应拦截器同样可以设置多个
  • 同样也可以给自定义axios 对象添加拦截器
  • 可以使用axios.interceptors. response.eject 来移除拦截器
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);
});

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

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

取消请求

  • 请求配置对象的 cancelToken 属性可以实现取消请求的功能, 每次请求执行时,会将取消请求的函数传给 cancelToken 的回调,执行这个取消函数,就可以将请求取消
//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;
  })
}

相关文章

  • vue学习笔记(1)——创建项目

    githubvue学习笔记(2)主要介绍项目的基本设置,如axios设置和项目颜色控制vue学习笔记(3)主要介绍...

  • vue学习笔记(3)——router

    githubvue学习笔记(1)主要介绍vue项目的创建vue学习笔记(2)主要介绍项目的基本设置,如axios设...

  • axios 学习笔记之context-type与 'applic

    axios 学习笔记之context-type与 'application/x-www-form-urlencod...

  • axios学习笔记

    一、axios的基本使用 get,获取数据 post,提交数据(表单提交以及文件上传) put,更新数据 (提交所...

  • axios 学习笔记

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

  • axios 的入门学习笔记

    这段时间接触了axios 。记录下学习笔记。 Promise based HTTP client for the ...

  • Axios文档阅读笔记.md

    最近项目中需要使用Axios,在阅读Axios文档时,发现文档笔记杂乱。现按照个人理解重新梳理。 Axios是什么...

  • vue----axios学习笔记

    前言:本地项目使用vue脚手架搭建的,使用git代码管理工具, 1.安装axios: npm install ax...

  • vue-axios中delete的使用

    这几天在学习使用 axios 的时候发现一个问题,在使用 axios.post 和 axios.put 时,后台均...

  • axios笔记

    前言 现在来说,axios 基本是 vue 项目的标配了;之前大家比较常用的是 vue-resource 小巧又好...

网友评论

      本文标题:axios 学习笔记

      本文链接:https://www.haomeiwen.com/subject/nsmwjrtx.html