axios 常用的几个方法

      Vue推荐使用axios 发送网络请求:最近重新开始做Vue项目,重新回归一下。从axios的几个方法开始吧。

      1. 安装: 既然是Vue项目,我还是选择常用的npm的方式

        $ npm install axios  (-d)

  2. 引入: const axios =  require('axios')  或者babel转化用ESmodule的方式  const axios = import('axios')

  3.请求: GET 请求,请求方式都非常灵活:

    axios.get('/user?ID=12345')   ----------------------   URL携带参数的方式

    axios.get('/user',{ params:{ ID:12345 } })  -------   参数对象的方式

    注意:返回的都是promise ------  下面是两个处理返回的方式

    a.  Promise.then().catch的形式 :

      axios.get('/user',{param:{ID:12345}}).then(response => {console.log(response)})

    b. async function getUser() {

      try {

        const response = await axios.get('/user',{ param:{ ID:12345} })

      } catch (e) { 

        console.log(e)

      }

     }    

    Post请求:按照参数对象方式传递即可

      axios.post('/user',{ name:"张三",age:"18"  })  注意:  这里是没有param 的,直接对象方式传递就可以了。

  4. 并发 请求 

    fucntion getUser(){

     axios.get('/user/1234')

            }

    fucntion getPermission (){

     axios.get('/user/1234/permissions')

            }

   axios.all([getUser,getPermission ]).then(axios.spread(function(acct,perms) {    ----.then方法中,调用axios.spread方法,参数为函数,该函数接受两个参数acct pe

      // 这两个参数,分别表示两个请求的返回。

    }))                      ------- 即Promise数组形式   catch函数捕获错误来源,待研究 ---

  5. 设置基本配置    包括baseUrl   和头部等   常用baseUrl    axios.creat( {config对象} )

    axios.creat({

      baseURL:'http://some-domain.com/api/',    // 基础url    通过webpack配置运行环境的判断,可以更改线上地址,开发地址前缀

      timeout:1000,             // 响应超时时间

      headers:{Content-Type:application/x-www-form-urlencoded }  // 请求头

    })

猜你喜欢

转载自www.cnblogs.com/yaya666/p/12128727.html