目录

1 axios 介绍

2 axios 的使用

2.1 axios 的安装

2.2 axios 的使用方法

2.2.1 axios 的get请求 (基本用法)

2.2.2 axios 的post请求 (基本用法)

2.2.3 axios 的 get 请求 (简写用法) 

2.2.4 axios 的 post 请求 (简写语法) 


1 axios 介绍

Axios 是一个基于 promise 的 HTTP 库,可以用在浏览器和 node.js 中。Axios 也是基于 promise 对 Ajax 的封装,axios 主要用于 mvvm 模式,而 Ajax 主要用于 mvc 模式。

2 axios 的使用

2.1 axios 的安装

1 使用 npm :

$ npm install axios

2 使用 bower :

$ bower install axios

3 使用 cdn :

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

2.2 axios 的使用方法

2.2.1 axios 的get请求 (基本用法)

① 使用默认 get 发送无参请求

axios({
    //默认使用 get 方法
      url:'' //这里为所要获取数据的url地址
    }).then(res => {
      console.log(res) //在命令行打印获取数据
    })

② 使用 get 发送无参请求

axios({
      //使用 method 确定使用方法
      method:'get',
      url:''
    }).then(res => {
      console.log(res)
    })

③ 使用默认 get 发送有参请求 

axios({
      // 在 url 地址后面加上 ? ,在 ? 后面加上要传递的参数
      url:'...dong?username=123'
    }).then(res => {
      console.log(res)
    })

 ④ 使用 get 发送有参请求

axios({
      // 在 url 地址后面加上 ? ,在 ? 后面加上要传递的参数
      method : 'get',
      url:'...dong?username=123'
    }).then(res => {
      console.log(res)
    })

⑤ 使用 params 发送 get 有参请求

axios({
      method : 'get',
      url:'...dong',
      params:{
        // 传递 username 参数 
        username : '123'      
}        
    }).then(res => {
      console.log(res)
    })

2.2.2 axios 的post请求 (基本用法)

① 使用 post 发送无参请求

axios({
      //使用 method 确定使用方法
      method:'post',
      url:''
    }).then(res => {
      console.log(res)
    })

 ② 使用 post 发送有参请求(直接使用这种 url 发送的方法不安全)

axios({
      // 在 url 地址后面加上 ? ,在 ? 后面加上要传递的参数
      method : 'post',
      url:'...dong?username=123'
    }).then(res => {
      console.log(res)
    })

③ 使用 params 发送 post 有参请求

axios({
      method : 'post',
      url:'...dong',
      params:{
        // 传递 username 参数 
        username : '123'      
}        
    }).then(res => {
      console.log(res)
    })

 注意:

当不使用 params 而使用 data 传递数据的时候,会发生传递数据为 null 的情况,这是由于 post 请求默认的数据格式是 application/json ,服务器解析不了。

面对这种情况有如下 3 种方法来解决问题:

1.如上所示不使用 data 而使用 params 传递数据,实际上这种方法相当于直接把 params 拼接在 url 后面,也是一种不完全的 post 请求

2.在简写语法中使用 "username = 123"

3.在服务器端进行解决,给接受的参数加上 @requestBody      

2.2.3 axios 的 get 请求 (简写用法) 

① get 的无参请求

axios.get('...qwe').then(res => {
      console.log(res)
// 使用 catch 处理错误的情况
    }).catch(err => {
      console.log(err)
    })

② get 的有参请求

// 使用 params 来传递参数
axios.get('...qwe',{params:{
      username:1,
      password:2
    }}).then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })

2.2.4 axios 的 post 请求 (简写语法) 

① post 的无参请求

axios.post('...qwe').then(res => {
      console.log(res)
// 使用 catch 处理错误的情况
    }).catch(err => {
      console.log(err)
    })

② post 的有参请求

// 直接使用 "username = 123" ,使用 params 会取 null
axios.post('...qwe',"username = 123&age = 10").then(res => {
      console.log(res)
    }).catch(err => {
      console.log(err)
    })