Axios学习笔记

Axios学习结构

Axios学习网址:起步 | Axios 中文文档 | Axios 中文网 (axios-http.cn)

1. Axios简介与特征

Axios简介 

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。
该框架主要就是用来请求HTTP接口的,底层就是传说中的Ajax。
​
axios的引言
    Axios 是一个  异步请求 技术
​
异步请求
    基于XMLHttpRequest对象发起的请求都是异步请求
​
异步请求特点
    请求之后页面不动,响应回来更新的是页面的局部,
    多个请求之间互不影响,并行执行
    系统架构 前后端分离架构系统   ---- 异步请求技术 ----->   Vue 全家桶系列

2. Axios基础入门

2.1 下载axios.js

网址:https://unpkg.com/axios/dist/axios.min.js

2.2 使用json-server创建接口

json-server用于Axios练习准备数据

1.使用npm install -g json-server                  安装json-server
2.使用json-server --watch --port 3000 db.json      启动db.json

db.json数据准备

{
  "course": [
    {
      "id": 1000,
      "course_name": "软件设计模式",
      "autor": "张三老师"
    },
    {
      "id": 1001,
      "course_name": "JavaSE基础",
      "autor": "王五老师"
    }]
}

2.3发起axios请求

//发起Ajax请求
axios({
    //请求类型
    method:'GET',//'POST','PUT','DELETE'
    url:'http://localhost:8080/hello',
}).then(response=>{
    //请求成功时处理响应
}).catch(error=>{
    //请求失败时处理响应
})

axios练习

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Axios练习1</title>
    <script src="axios.js"></script>
</head>
<body>
    <button class="btn1">按钮GET</button>
    <button class="btn2">按钮POST</button>
</body>
<script>
    let btn1=document.querySelector(".btn1");
    let btn2=document.querySelector(".btn2");
    btn1.onclick=function(){
        //发送axios请求
        axios({
            //请求方式
            methods:'GET',//可以是POST,DELETE等等
            //URL
            url:' http://localhost:3000/course',
        }).then(response=>{
            console.log(response);
        }).catch(error=>{
            console.log(error);
        })
    }
    
    btn2.onclick=function(){
       //发送axios请求
        axios({
            //请求方式
            method:'POST',
            //URL
            url:'http://localhost:3000/course',
            //设置请求体
            data:{
                course_name:"SpringBoot框架学习",
                author:"李四老师"
            }
        }).then(response=>{
            console.log("0000");
            console.log(response);
        }).catch(error=>{
            console.log(error);
        })
    }
</script>
</html>

3. Axios方法请求

3.1 get方法请求

axios.get(url[,{参数}])
     .then(response => {
        在这里处理接口的正常响应
     })
     .catch(error => {
        在这里处理接口的异常响应
     })
     
 参数说明
    url     请求API的地址
    参数     我们可以在该参数里配置我们需要设置的params参数、headers参数等

3.2 post方法请求

axios.post(url, body[,参数])
     .then(response => {
        在这里处理接口的正常响应
     })
     .catch(error => {
        在这里处理接口的异常响应
     })
     
 参数说明
    body    也叫“请求体”,我们一般就把需要传递的参数放到请求休里面,通常“请求体”一般为json格式。

GET&&POST

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Axios练习2</title>
    <script src="axios.js"></script>
</head>
<body>
    <button class="btn1">按钮GET</button>
    <button class="btn2">按钮POST</button>
</body>
<script>
    let btn1=document.querySelector(".btn1");
    let btn2=document.querySelector(".btn2");
    btn1.onclick=function(){
        axios.get('http://localhost:3000/course')
             .then(response=>{
                 console.log(response);
             })
             .catch(error=>{
                console.log(error);
             })
    }
    btn2.onclick=function(){
       axios.post('http://localhost:3000/course',{
            course_name:"Vue框架学习",
            author:"李玲老师"
        }).then(response=>{
            console.log(response);
        }).catch(error=>{
            console.log(error);
        })
    }
</script>
</html>

4. Axios实例

4.1 实例练习

const axiosInstance=axios.create({
    //设置一些配置如:baseURL,tiemout
})

axios实例练习

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Axios练习1</title>
    <script src="axios.js"></script>
</head>
<body>
    <button class="btn1">按钮GET请求一个接口</button>
    <button class="btn2">按键GET请求另一个接口</button>
</body>
<script>
    let btn1=document.querySelector(".btn1");
    let btn2=document.querySelector(".btn2");
​
    // 创建axios实例request1
    const request1=axios.create({
        baseURL:'http://localhost:3000',
    })
    
    btn1.onclick=function(){
        request1.get('/course')
        .then(response=>{
            console.log(response);
        }).catch(error=>{
            console.log(error);
        })
    }
​
    btn2.onclick=function(){
        request1.get('/student')
        .then(response=>{
            console.log(response);
        }).catch(error=>{
            console.log(error);
        })
    }
</script>
</html>

4.2 实例方法

以下是可用的实例方法。指定的配置将与实例的配置合并。

axios#request(config)
axios#get(url[, config])
axios#delete(url[, config])
axios#head(url[, config])
axios#options(url[, config])
axios#post(url[, data[, config]])
axios#put(url[, data[, config]])
axios#patch(url[, data[, config]])
axios#getUri([config])

5. Axios默认配置

5.1 axios官网配置

{
  // `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` 表示跨域请求时是否需要使用凭证
  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 // 默认值
​
}

5.2 axios配置练习

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Axios练习3</title>
    <script src="axios.js"></script>
</head>
<body>
    <button class="btn1">按钮GET请求</button>
</body>
<script>
    /*
    axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
    axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
    */
    let btn1=document.querySelector(".btn1");
    axios.defaults.method='GET';
    axios.defaults.baseURL='http://localhost:3000';
​
    btn1.onclick=function(){
        axios({
            url:'/student'
        }).then(response=>{
            console.log(response);
        })
    }
</script>
</html>

响应结构

{
  // `data` 由服务器提供的响应
  data: {},
​
  // `status` 来自服务器响应的 HTTP 状态码
  status: 200,
​
  // `statusText` 来自服务器响应的 HTTP 状态信息
  statusText: 'OK',
​
  // `headers` 是服务器响应头
  // 所有的 header 名称都是小写,而且可以使用方括号语法访问
  // 例如: `response.headers['content-type']`
  headers: {},
​
  // `config` 是 `axios` 请求的配置信息
  config: {},
​
  // `request` 是生成此响应的请求
  // 在node.js中它是最后一个ClientRequest实例 (in redirects),
  // 在浏览器中则是 XMLHttpRequest 实例
  request: {}
}
axios.get('/student')
  .then(function (response) {
    console.log(response.data);
    console.log(response.status);
    console.log(response.statusText);
    console.log(response.headers);
    console.log(response.config);
  });

6. Axios拦截器

6.1 请求拦截器

axios.interceptors.request.use

6.2 响应拦截器

axios.interceptors.response.use

// 添加请求拦截器
axios.interceptors.request.use(function (config) {
    // 在发送请求之前做些什么
    return config;
  }, function (error) {
    // 对请求错误做些什么
    return Promise.reject(error);
  });
​
// 添加响应拦截器
axios.interceptors.response.use(function (response) {
    // 2xx 范围内的状态码都会触发该函数。
    // 对响应数据做点什么
    return response;
  }, function (error) {
    // 超出 2xx 范围的状态码都会触发该函数。
    // 对响应错误做点什么
    return Promise.reject(error);
  });

响应器

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Axios练习4</title>
    <script src="axios.js"></script>
</head>
<body>
    <button class="btn1">按钮GET请求</button>
</body>
<script>
    let btn1=document.querySelector(".btn1");
​
    axios.defaults.method='GET';
    axios.defaults.baseURL='http://localhost:3000';
​
        // 添加请求拦截器
    axios.interceptors.request.use(function (config) {
        // 在发送请求之前做些什么
        console.log("请求成功");
        return config;
    }, function (error) {
        // 对请求错误做些什么
        return Promise.reject(error);
    });
​
    // 添加响应拦截器
    axios.interceptors.response.use(function (response) {
        // 对响应数据做点什么
        console.log("响应成功");
        return response;
    }, function (error) {
        // 对响应错误做点什么
        return Promise.reject(error);
    });
​
    btn1.onclick=function(){
        axios({
            url:'/student'
        }).then(response=>{
            console.log(response);
        })
    }
</script>
</html>

6.3 axios实例拦截器

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

7. Axios并发请求

function getUserAccount() {
  return axios.get('/user/12345');
}
​
function getUserPermissions() {
  return axios.get('/user/12345/permissions');
}
​
Promise.all([getUserAccount(), getUserPermissions()])
  .then(function (results) {
    const acct = results[0];
    const perm = results[1];
  });

8. Axios错误处理

catch(error=>{
    //错误处理
    
    //使用 validateStatus 配置选项,可以自定义抛出错误的 HTTP code。
    validateStatus: function (status) {
        return status < 500; // 处理状态码小于500的情况
    }
    
    //使用 toJSON 可以获取更多关于HTTP错误的信息。
    console.log(error.toJSON);
})

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我愿为一粒沙

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值