axios基础

准备工作

起步 | Axios 中文文档 | Axios 中文网

http://github.com/typicode/json-server

json-server:搭建服务器端

vs中安装json-server命令行代码:npm install -g json-server(全局安装)

创建json文件(以db.json为例),注意是json格式(尚硅谷axios代码有,自己看)

启动json-server代码:json-server --watch db.json

 

 我们也可以自己修改路径,如修改路径来根据id选择访问的数据

 一、axios介绍

1、axios特点及安装

1. 基于 xhr + promise 的异步 ajax 请求库

2. 浏览器端、node 端都可以使用

    浏览器中通过axios向服务端发送ajax请求;node.js通过axios发送http请求

3. 支持请求/响应拦截器

4. 支持请求取消

5. 请求/响应数据转换

6. 批量发送多个请求

项目中安装方式:

npm add axios

yarn add axios

学习也就是接下来我们采用CDN引入axios,而非上面的方法:

<script src="https://cdn.jsdelivr.net/npm/axios@1.1.2/dist/axios.min.js"></script>

<script src="https://unpkg.com/axios@1.1.2/dist/axios.min.js"></script>

上面的网站获取资源可能较慢,可以在网站:axios (v1.3.6) - Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 Node.js 中。 | BootCDN - Bootstrap 中文网开源项目免费 CDN 加速服务搜索axios点击复制即可

 2、axios基本使用

GET请求:读取

POST请求:添加

PUT请求:更新

DELECT请求:删除

案例:

 2.1GET请求

<div class="container">
    <h2 class="page-header">基本使用</h2>
    <button class="btn btn-primary"> 发送GET请求 </button>
    <button class="btn btn-warning" > 发送POST请求 </button>
    <button class="btn btn-success"> 发送 PUT 请求 </button>
    <button class="btn btn-danger"> 发送 DELETE 请求 </button>
</div>
<script>
    //获取按钮
    const btns = document.querySelectorAll('button');
    //第一个
    btns[0].onclick = function(){
        //发送 AJAX 请求
        axios({
            //请求类型
            method: 'GET',
            //URL,请求的是post文章的第二篇信息
            url: 'http://localhost:3000/posts/2',
        }).then(response => {
            console.log(response);
        });
    }
</script>

 2.2POST请求

POST向服务器新增、添加数据,这里是在posts文章中新增第三篇文章

//添加一篇新的文章
btns[1].onclick = function(){
   //发送 AJAX 请求
   axios({
       //请求类型
       method: 'POST',
       //URL,这里最后是/posts
       url: 'http://localhost:3000/posts',
       //设置请求体,看一看ajax内容,不需要添加id,自动递增为3
       data: {
           title: "今天天气不错, 还挺风和日丽的",
           author: "张三"
       }
    }).then(response => {
       console.log(response);
    });
}

 点击按钮后可以进最开始的db.json看,发现posts是有新内容出现的

2.3PUT请求

PUT请求:更新数据。例如修改上面posts文章第三篇的author的值

//更新数据
btns[2].onclick = function(){
    //发送 AJAX 请求
    axios({
        //请求类型
        method: 'PUT',
        //URL,要指定到posts/3,不写3就又是新增
        url: 'http://localhost:3000/posts/3',
        //设置请求体
        data: {
            title: "今天天气不错, 还挺风和日丽的",
            author: "李四"
        }
    }).then(response => {
        console.log(response);
    });
}

 2.4DELECT请求

DELECT请求: 删除数据,和上面差不多,看看就好

//删除数据
btns[3].onclick = function(){
    //发送 AJAX 请求
    axios({
        //请求类型
        method: 'delete',
        //URL
        url: 'http://localhost:3000/posts/3',
    }).then(response => {
        console.log(response);
    });
}

以GET为例,输出的内容可以好好看看

3、axios请求对象

data和params都可以传递参数,具体看下面文章

Axios post 传参的params 与data 的两种形式(根据java后台接口来选择)_axios post data_bug收集的博客-CSDN博客

即在调用axios在调用时所接收的参数对象,上面最后输出的config当中

axios的配置对象(config)包含以下属性:

{
  // `url` 是用于请求的服务器 URL
  url: '/user',
 
  // `method` 是创建请求时使用的方法
  method: 'get', // 默认值
 
  // `baseURL` 将自动加在 `url` 前面,除非 `url` 是一个绝对 URL。
  // 它可以通过设置一个 `baseURL` 便于为 axios 实例的方法传递相对 URL
  baseURL: 'https://some-domain.com/api/',
 
  // `transformRequest` 允许在向服务器发送前,修改请求数据
  // 它只能用于 'PUT', 'POST' 和 'PATCH' 这几个请求方法
  // 数组中最后一个函数必须返回一个字符串, 一个Buffer实例,ArrayBuffer,FormData,或 Stream
  transformRequest: [function (data, headers) {
    // 对发送的 data 进行任意转换处理
    return data;
  }],
 
  // `transformResponse` 在传递给 then/catch 前,允许修改服务器传回的响应数据
  transformResponse: [function (data) {
    // 对接收的 data 进行任意转换处理
    return data;
  }],
 
  // 自定义请求头
  headers: {'X-Requested-With': 'XMLHttpRequest'},
 
  // `params` 是与请求一起发送的 URL 参数
  // 必须是一个简单对象或 URLSearchParams 对象
  params: {
    ID: 12345
  },
 
  // `paramsSerializer`是可选方法,主要用于序列化`params`
  // (e.g. https://www.npmjs.com/package/qs, http://api.jquery.com/jquery.param/)
  paramsSerializer: function (params) {
    return Qs.stringify(params, {arrayFormat: 'brackets'})
  },
 
  // `data` 是作为请求体被发送的数据
  // 仅适用 'PUT', 'POST', 'DELETE 和 'PATCH' 请求方法
  // 在没有设置 `transformRequest` 时,则必须是以下类型之一:
  // - string, plain object, ArrayBuffer, ArrayBufferView, URLSearchParams
  // - 浏览器专属: FormData, File, Blob
  // - Node 专属: Stream, Buffer
  data: {
    firstName: 'Fred'
  },
  
  // 发送请求体数据的可选语法
  // 请求方式 post
  // 只有 value 会被发送,key 则不会
  data: 'Country=Brasil&City=Belo Horizonte',
 
  // `timeout` 指定请求超时的毫秒数。
  // 如果请求时间超过 `timeout` 的值,则请求会被中断
  timeout: 1000, // 默认值是 `0` (永不超时)
 
  // `withCredentials` 表示跨域请求时是否需要使用凭证(是否携带cookie,false为不携带)
  withCredentials: false, // default
 
  // `adapter` 允许自定义处理请求,这使测试更加容易。
  // 返回一个 promise 并提供一个有效的响应 (参见 lib/adapters/README.md)。
  adapter: function (config) {
    /* ... */
  },
 
  // `auth` HTTP Basic Auth
  auth: {
    username: 'janedoe',
    password: 's00pers3cret'
  },
 
  // `responseType` 表示浏览器将要响应的数据类型
  // 选项包括: 'arraybuffer', 'document', 'json', 'text', 'stream'
  // 浏览器专属:'blob'
  responseType: 'json', // 默认值
 
  // `responseEncoding` 表示用于解码响应的编码 (Node.js 专属)
  // 注意:忽略 `responseType` 的值为 'stream',或者是客户端请求
  // Note: Ignored for `responseType` of 'stream' or client-side requests
  responseEncoding: 'utf8', // 默认值
 
  // `xsrfCookieName` 是 xsrf token 的值,被用作 cookie 的名称(实行保护作用)
  xsrfCookieName: 'XSRF-TOKEN', // 默认值
 
  // `xsrfHeaderName` 是带有 xsrf token 值的http 请求头名称
  xsrfHeaderName: 'X-XSRF-TOKEN', // 默认值
 
  // `onUploadProgress` 允许为上传处理进度事件
  // 浏览器专属
  onUploadProgress: function (progressEvent) {
    // 处理原生进度事件
  },
 
  // `onDownloadProgress` 允许为下载处理进度事件
  // 浏览器专属
  onDownloadProgress: function (progressEvent) {
    // 处理原生进度事件
  },
 
  // `maxContentLength` 定义了node.js中允许的HTTP响应内容的最大字节数
  maxContentLength: 2000,
 
  // `maxBodyLength`(仅Node)定义允许的http请求内容的最大字节数
  maxBodyLength: 2000,
 
  // `validateStatus` 定义了对于给定的 HTTP状态码是 resolve 还是 reject promise。
  // 如果 `validateStatus` 返回 `true` (或者设置为 `null` 或 `undefined`),
  // 则promise 将会 resolved,否则是 rejected。
  validateStatus: function (status) {
    return status >= 200 && status < 300; // 默认值
  },
 
  // `maxRedirects` 定义了在node.js中要遵循的最大重定向数。
  // 如果设置为0,则不会进行重定向
  maxRedirects: 5, // 默认值
 
  // `socketPath` 定义了在node.js中使用的UNIX套接字。
  // e.g. '/var/run/docker.sock' 发送请求到 docker 守护进程。
  // 只能指定 `socketPath` 或 `proxy` 。
  // 若都指定,这使用 `socketPath` 。
  socketPath: null, // default
 
  // `httpAgent` and `httpsAgent` define a custom agent to be used when performing http
  // and https requests, respectively, in node.js. This allows options to be added like
  // `keepAlive` that are not enabled by default.
  httpAgent: new http.Agent({ keepAlive: true }),
  httpsAgent: new https.Agent({ keepAlive: true }),
 
  // `proxy` 定义了代理服务器的主机名,端口和协议。
  // 您可以使用常规的`http_proxy` 和 `https_proxy` 环境变量。
  // 使用 `false` 可以禁用代理功能,同时环境变量也会被忽略。
  // `auth`表示应使用HTTP Basic auth连接到代理,并且提供凭据。
  // 这将设置一个 `Proxy-Authorization` 请求头,它会覆盖 `headers` 中已存在的自定义 `Proxy-Authorization` 请求头。
  // 如果代理服务器使用 HTTPS,则必须设置 protocol 为`https`
  proxy: {
    protocol: 'https',
    host: '127.0.0.1',
    port: 9000,
    auth: {
      username: 'mikeymike',
      password: 'rapunz3l'
    }
  },
 
  // see https://axios-http.com/zh/docs/cancellation
  cancelToken: new CancelToken(function (cancel) {
  }),
 
  // `decompress` indicates whether or not the response body should be decompressed 
  // automatically. If set to `true` will also remove the 'content-encoding' header 
  // from the responses objects of all decompressed responses
  // - Node only (XHR cannot turn off decompression)
  decompress: true // 默认值
 
}

4、axios默认配置

实际项目,经常会是许多请求的method、get、baseURL等配置都是相同的,为了避免每次请求都重复写相同的代码,所以说设置默认配置。以后请求时在默认配置中有的东西便可以直接不用写。

<script>
    //获取按钮
    const btns = document.querySelectorAll('button');
    //默认配置
    axios.defaults.method = 'GET';//设置默认的请求类型为 GET
    axios.defaults.baseURL = 'http://localhost:3000';//协议、域名、接口设置基础 URL
    axios.defaults.params = {id:100};
    axios.defaults.timeout = 3000;//

    btns[0].onclick = function(){
        axios({
            url: '/posts'
        }).then(response => {
            console.log(response);
        })
    }
</script>

5、axios创建实例对象

下面创建了duanzi和another两个实例,好处是两个实例可以对不同的请求地址发送请求

请求方式也和axios一样,有两种,有一种被注释了

<script>
    //获取按钮
    const btns = document.querySelectorAll('button');
    
    //创建实例对象  /getJoke
    const duanzi = axios.create({
        baseURL: 'https://api.apiopen.top',
        timeout: 2000
    });
    
    const another = axios.create({
        baseURL: 'https://b.com',
        timeout: 2000
    });
    //这里  duanzi 与 axios 对象的功能几近是一样的
    // duanzi({
    //     url: '/getJoke',
    // }).then(response => {
    //     console.log(response);
    // });

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

6、axios拦截器

  1. 请求拦截器 在请求发送前进行必要操作处理,例如添加统一cookie、请求体加验证、设置请求头等,相当于是对每个接口里相同操作的一个封装;

  2. 响应拦截器 同理,响应拦截器也是如此功能,只是在请求得到响应之后,对响应体的一些处理,通常是数据统一处理等,也常来判断登录失效等。

 请求拦截器和响应拦截器都有成功和失败两个回调函数,注意不是字面意思的拦截成功,拦截器不是拦截请求的意思,而是上面说了对请求和响应做要写处理。所以说请求成功即下面的例子可以看看是走的那一条路线。

// 下面请求和响应拦截器,都有use方法其内有两个回调方法,分别是成功和失败

// 设置请求拦截器  config 配置对象
axios.interceptors.request.use(function (config) {
    console.log('请求拦截器 成功 - 1号');
    //修改 config 中的参数,timeout这些都可以在这里改
    config.params = {a:100};
    return config;
}, function (error) {
    console.log('请求拦截器 失败 - 1号');
    return Promise.reject(error);
});

// 设置响应拦截器
axios.interceptors.response.use(function (response) {
    console.log('响应拦截器 成功 1号');
    return response.data;
}, function (error) {
    console.log('响应拦截器 失败 1号')
    return Promise.reject(error);
});

//发送请求
axios({
    method: 'GET',
    url: 'http://localhost:3000/posts'
}).then(response => {
    console.log('自定义回调处理成功的结果');
    console.log(response);
});

 拦截器执行顺序问题:

        // 设置请求拦截器  config 配置对象
        axios.interceptors.request.use(function (config) {
            console.log('请求拦截器 成功 - 1号');
            return config;
        }, function (error) {
            console.log('请求拦截器 失败 - 1号');
            return Promise.reject(error);
        });

        axios.interceptors.request.use(function (config) {
            console.log('请求拦截器 成功 - 2号');
            return config;
        }, function (error) {
            console.log('请求拦截器 失败 - 2号');
            return Promise.reject(error);
        });

        // 设置响应拦截器
        axios.interceptors.response.use(function (response) {
            console.log('响应拦截器 成功 1号');
            return response;
        }, function (error) {
            console.log('响应拦截器 失败 1号')
            return Promise.reject(error);
        });

        axios.interceptors.response.use(function (response) {
            console.log('响应拦截器 成功 2号')
            return response;
        }, function (error) {
            console.log('响应拦截器 失败 2号')
            return Promise.reject(error);
        });

        //发送请求
        axios({
            method: 'GET',
            url: 'http://localhost:3000/posts'
        }).then(response => {
            console.log('自定义回调处理成功的结果');
            console.log(response);
        });

7、axios取消请求

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值