基於http客戶端的promise,面向瀏覽器和nodejsjavascript
瀏覽器端發起XMLHttpRequests請求vue
node端發起http請求java
支持Promise APInode
監聽請求和返回ios
轉化請求和返回npm
取消請求json
自動轉化json數據axios
客戶端支持抵禦promise
使用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=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) })