Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中
在Vue中使用,最好安裝兩個模塊axios 和vue-axios
$npm install axios vue-axios --save
然后引用并使用模塊
import Axios from 'axios'import VueAxios from 'vue-axios'Vue.use(VueAxios,Axios)
在組件中通過如下方式進行使用
this.$http[method]()
1、可以從瀏覽器中創建XHR對象
2、可以從nodeJS中創建HTTP請求
3、支持Promise API
4、可以攔截請求和響應
5、可以轉換請求數據和響應數據
6、可以取消請求
7、可以自動轉換JSON數據
8、客戶端支持防御XSRF
下面是一些簡單的請求實例
僅僅向后端請求數據
axios.get('index.php') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });通過URL向后端發送數據,要使用params屬性,params屬性包含即將與請求一起發送的數據
運行下列代碼后,請求URL變更為index.php?id=12345&text=%E5%B0%8F%E7%81%AB%E6%9F%B4
axios.get('index.php',{ params:{ id:12345, text:'jb51' }}).then((response)=>{ console.log(response)}).catch((error)=>{ console.log(error)})當然,也可以把數據直接寫到URL中
// 為給定 ID 的 user 創建請求axios.get('/user?ID=12345') .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); });一般來說,post請求更多的是要提交數據,params屬性里的數據會出現在請求主體中
[注意]如果是axios.create()方法中的params屬性,則其里面的數據會出現在URL參數中
但實際上,post方法不需要使用params屬性,它的第二個參數就是要發送的數據
axios.post('index.php',{ id:12345, text:'jb51'}).then((response)=>{ console.log(response)}).catch((error)=>{ console.log(error)})多并發請求
function getUserAccount() { return axios.get('/user/12345');}function getUserPermissions() { return axios.get('/user/12345/permissions');}axios.all([getUserAccount(), getUserPermissions()]) .then(axios.spread(function (acct, perms) { // acct為第一個請求的結果,perms為第二個請求的結果 }));可以通過向 axios 傳遞相關配置來創建請求
axios(config)// 發送 POST 請求axios({ method: 'post', url: '/user/12345', data: { firstName: 'Fred', lastName: 'Flintstone' }});axios(url[,config])// 發送 GET 請求(默認的方法)axios('/user/12345');
新聞熱點
疑難解答
圖片精選