1. 程式人生 > 其它 >從零開始學VUE之網路模組(Axios)

從零開始學VUE之網路模組(Axios)

Axios

功能特點

  • 在瀏覽器中傳送XHR請求
  • 在Node.js中傳送http請求
  • 支援 Promise API
  • 攔截請求和響應

支援多種請求方式

  • axios(config)
  • axios.request(config)
  • axios.get(url[,config])
  • axios.delete(url[,config])
  • axios.head(url[,config])
  • axios.post(url,data[,config])
  • axios.put(url,data[,config])
  • axios.patch(url,data[,config])

安裝

npm install axios --save

測試地址[老師的]

http://123.207.32.32:8000/home/multidata

簡單使用

// 匯入 axios
import axios from "axios";

// 使用
axios({
  url:'http://123.207.32.32:8000/home/multidata'
}).then(res => {
  console.log(res);
})

傳遞引數

(拼接URL後面)

axios({
  url:'http://123.207.32.32:8000/home/data',
  params:{
    type:'pop',
    page:1
  }
}).then(res 
=> { console.log(res); })

傳送併發請求

/**
 * 傳送多請求
 */
axios.all([
  axios({
    url:'http://123.207.32.32:8000/home/multidata'
  }),
  axios({
    url:'http://123.207.32.32:8000/home/multidata'
  })
]).then(res => {
  // 返回結果res是一個數組 [0] 就是第一個請求返回的結果 [1]...
  console.log(res);
})
axios.all([
  axios({
    url:'http://123.207.32.32:8000/home/multidata'
  }),
  axios({
    url:
'http://123.207.32.32:8000/home/multidata' }) // 可以通過 axios.spread展開返回結果 ]).then(axios.spread((res1,res2) => { // 返回結果res是一個數組 [0] 就是第一個請求返回的結果 [1]... console.log(res1); console.log(res2); }))

抽取預設配置

/**
 * 預設配置
 */
// 預設字首URL
axios.defaults.baseURL = 'http://123.207.32.32:8000'
// 超時時間 單位:毫秒
axios.defaults.timeout = 5000

/**
 * 簡單使用
 */
axios({
  url:'/home/multidata'
}).then(res => {
  console.log(res);
})

常見的配置

  • 請求地址
  • url:'/user'
  • 請求型別
  • method:'get'
  • 請求路徑
  • baseURL:'https://www.baidu.com'
  • 請求前的資料處理
  • transformRequest:[function(data){}]
  • 請求後的資料處理
  • transformResponse:[function(data){}]
  • 自定義的請求頭
  • headers:{'x-Requested-With':'XMLHttpRequest'},
  • URL查詢物件
  • params:{id:12}
  • 查詢物件序列化函式
  • paramsSerializer:function(params){}
  • request body
  • data:{key:'aa'}
  • 超時設定s
  • timeout : 1000
  • 跨域是否攜帶Token
  • withCredentials:false
  • 自定義請求處理
  • adapter:function(resolve,reject,config){}
  • 身份驗證資訊
  • auth:{uname:'彼岸舞',pwd:'111'}
  • 響應的資料格式
  • json | blob | document | arraybuffer | text | stream
  • responseType : 'json'

建立對應的Axios的例項

let config = {
  baseURL:'http://123.207.32.32:8000',
  timeout:5000
};
let axiosInstance = axios.create(config);
axiosInstance({
  url:'/home/multidata'
}).then(res => {
  console.log(res);
})

攔截器

let config = {
  baseURL:'http://123.207.32.32:8000',
  timeout:5000
};
let axiosInstance = axios.create(config);

// 請求攔截器
axiosInstance.interceptors.request.use(
  // 攔截請求時的 config
  config => {
    console.log(config);
    return config;
  },
  // 攔截請求失敗的error 一般請求不會失敗的
  error => {

  }
)
// 響應攔截器
axiosInstance.interceptors.response.use(
  // 請求返回的資料
  res => {
    console.log(res);
    // 做資料過濾 只返回後端返回的data
    return res.data;
  },
  // 請求失敗的error
  error => {
    console.log(error);
  }
)

作者:彼岸舞

時間:2021\06\28

內容關於:VUE

本文屬於作者原創,未經允許,禁止轉發