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 格式。