1. 程式人生 > >Vue中axios的使用技巧配置項詳解

Vue中axios的使用技巧配置項詳解

www 模塊 模擬 傳遞 all 字符串 給定 ans 必須

使用axios首先要下載axios模塊包

npm install axios --save

其次需要在使用的文件中引入

import axios from ‘axios‘

一、調用axios常見兩種方法(此處使用easy-mock模擬數據接口):

//方法1
      axios({
        method: ‘post‘,
        url:‘http://easy-mock.com/mock/596077559adc231f357bcdfb/axios/test-post-axios‘
      })
      .then((response)=>{
          console.log(response.data)
      })
      .
catch((error)=>{ console.log(error) })
//方法2
    axios.post(‘http://easy-mock.com/mock/596077559adc231f357bcdfb/axios/test-post-axios‘,{
      miaov:"課堂"  //發送的數據
    })
      .then((response)=>{
        console.log(response.data)
      })
      .catch((error)=>{
        console.log(error)
      })

註意:

方法一中向後臺發送數據時:

//get方式發送數據
            axios.get(‘https://easy-mock.com/mock/5a883cccbf160328124e8204/example/mock‘, {
                params: {
                    pomelo: ‘tt‘,
                    test: ‘test‘
                }
            }).then((response) => {
                console.log(response)
            }).
catch((error) => { console.log(error) }) //post方式發送數據 axios.post(‘https://easy-mock.com/mock/5a883cccbf160328124e8204/example/mock‘, { pomelo: ‘tt‘, test: ‘test‘ }).then((response) => { console.log(response) }).catch((error) => { console.log(error) })

二、自定義請求實例

//常見請求實例配置項
{
     baseURL: ‘’,  //基礎URL
     timeout:1000,  //請求延時時間
     headers {‘X-Requested-With‘: ‘XMLHttpRequest‘},   //自定義請求頭內容
     responseType: ‘json‘,  //請求數據類型包括  ‘arraybuffer‘, ‘blob‘, ‘document‘, ‘json‘, ‘text‘, ‘stream‘
     params: {},  //無論請求為何種類型,在params中的屬性都會以key=value的格式在urlzhong拼接
     transformRequest: [function(data){
         return data
     }],   // 只適用於 POST,PUT,PATCH,transformRequest` 允許在向服務器發送前,修改請求數據。後面數組中的函數必須返回一個字符串,或 ArrayBuffer,或 Stream
     transformResponse: [function(data){
         return data
     }],   //transformResponse` 在傳遞給 then/catch 前,允許修改響應數據
     validateStatus: function(status){
  return status < 400 //狀態碼小於400時均為成功(返回true)
}, //validateStatus` 定義對於給定的HTTP 響應狀態碼是 resolve 或 reject promise 。如果 `validateStatus` 返回 `true` (或者設置為 `null` 或 `undefined`),promise 將被 resolve; 否則,promise 將被 rejecte cancelToken //取消請求,下文詳細說明 }

使用自定義請求實例時需要先創建對象

var HTTP = axios.create({})   // {}中放入上文中的配置項

使用transformRequest將數據格式改為key=value的格式

import queryString from ‘queryString‘  //轉換格式包,無需下載


  var HTTP = axios.create({
    baseURL:‘http://easy-mock.com/mock/596077559adc231f357bcdfb/axios/‘,
    timeout: 1000,
    responseType:‘json‘,
    headers:{
      ‘custome-header‘: ‘miaov‘,
      ‘content-type‘:‘application/x-www-form-urlencoded‘   //轉換為key=value的格式必須增加content-type
    },
    transformRequest:[function(data){
        console.log(data)
      data.age = 30;  //發送之前增加的屬性
      return queryString.stringify(data);    //利用對應方法轉換格式
    }]
  })

Vue中axios的使用技巧配置項詳解