Axios

axios的簡介

axios 是一個基于Promise 用于瀏覽器和 nodejs 的 HTTP 客戶端,它本身具有以下特征:

  • 從瀏覽器中創(chuàng)建 XMLHttpRequest
  • 從 node.js 發(fā)出 http 請求
  • 支持 Promise API
  • 攔截請求和響應(yīng)
  • 轉(zhuǎn)換請求和響應(yīng)數(shù)據(jù)
  • 取消請求
  • 自動轉(zhuǎn)換JSON數(shù)據(jù)
  • 客戶端支持防止 CSRF/XSRF
安裝 axios

npm install axios

引入加載

import axios from 'axios'

將axios全局掛載到Vue原型上

Vue.prototype.$http = axios;

發(fā)出請求 以Vue中文社區(qū)為例子(官網(wǎng)提供的 API)
getData () {
  this.$http.get('https://www.vue-js.com/api/v1/topics')
    .then((response) => {
      console.log(response)
    })
    .catch((error) => {
      console.log(error)
    })
}

axios 是基于 Promise 的,可以使用 then 和 catch 。

在發(fā)送請求時,可以傳遞參數(shù),參數(shù)的傳遞有兩種方式:

  • 對象
getData () {
  this.$http.get('https://www.vue-js.com/api/v1/topics, {
    params: {
      page: 1,  // 頁碼
      limit: 20  // 每頁顯示的數(shù)量
    }
  }')
    .then((response) => {
      console.log(response)
    })
    .catch((error) => {
      console.log(error)
    })
}
  • 類似于查詢字符串
getData () {
  this.$http.get('https://www.vue-js.com/api/v1/topics?page=1&limit=20')
    .then((response) => {
      console.log(response)
    })
    .catch((error) => {
      console.log(error)
    })
}
axios 發(fā)送 post 請求

POST傳遞數(shù)據(jù)有兩種格式:

  • form--data ?page=1&limit=48
  • x--www--form--urlencoded { page: 1,limit: 10 }
  • 在axios中,post請求接收的參數(shù)必須是form--data
    qs插件—-qs.stringify
postData () {
  this.$http.post(url, {
    params: {
      page: 1,
      limit: 20
    }
  })
    .then((response) => {
      console.log(response)
    })
    .catch((error) => {
      console.log(error)
    })
}

這種寫法是不可行的,后臺接收到的數(shù)據(jù)會是 x-www-form-urlencoded 格式。

使用 qs 插件

安裝 qs 插件
npm install qs
引入 qs:
import qs from 'qs'

postData () {
  this.$http.post(url, qs.stringify({
    params: {
      page: 1,
      limit: 20
    }
  }))
    .then((response) => {
      console.log(response)
    })
    .catch((error) => {
      console.log(error)
    })
}

使用 qs.stringify 方法,將對象轉(zhuǎn)變成字符串,后臺接收到的是 form-data 格式。

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容