axios
基于http客戶端的promise,面向瀏覽器和nodejs
特色
-
瀏覽器端發起XMLHttpRequests請求
-
node端發起http請求
-
支持Promise API
-
監聽請求和回傳
-
轉化請求和回傳
-
取消請求
-
自動轉化json資料
-
客戶端支持抵御
安裝
使用npm:
npm install axios --save
為了解決post默認使用的是application/json請求資料 ,導致請求引數無法傳遞到后臺,所以還需要安裝一個插件QS,此插件將application/json轉換為application/x-www-from-urlencoded
npm install qs --save
一個命令全部解決
npm install --save axios vue-axios qs
使用
修改原型鏈
首先在 main.js 中引入 axios
import Axiso from 'axiso'
這時候如果在其它的組件中,是無法使用 axios 命令的,但如果將 axios 改寫為 Vue 的原型屬性,就能解決這個問題
Vue.prototype.$axios= Axios
配置好了之后就可以全域使用了
post請求轉換
import QS from 'qs'
if(config.method=='post'){
config.data=https://www.cnblogs.com/eternityz/p/QS.stringify(config.data);//防止post請求引數無法傳到后臺
}
實體使用:
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)
})
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)
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/150732.html
標籤:JavaScript
上一篇:vue中報錯Do not use built-in or reserved HTML elements as component id details
