日韩av黄I国产麻豆传媒I国产91av视频在线观看I日韩一区二区三区在线看I美女国产在线I麻豆视频国产在线观看I成人黄色短片

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 >

Axios的基本使用

發布時間:2025/3/19 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Axios的基本使用 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

Axios

Axios 是一個基于 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。

特點

支持瀏覽器和node.js
支持promise
能攔截請求和響應
能轉換請求和響應數據
能取消請求
自動轉換JSON數據
瀏覽器端支持防止CSRF(跨站請求偽造)

安裝

npm安裝

$ npm install axios


bower安裝

$ bower install axios


通過cdn引入

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

引入

? import Axios from "axios"Vue.prototype.$axios = Axios

使用

執行GET請求

mounted(){this.$axios.get("http://www.wwtliu.com/sxtstu/blueberrypai/getChengpinInfo.php").then(res => {console.log(res.data);}).catch(error => {console.log(error);})}

上面的請求也可以這樣寫:

axios.get('/user', {params: {ID: 12345}}).then(function (response) {console.log(response);}).catch(function (error) {console.log(error);});

執行POST請求

axios.post('/user', {firstName: 'Fred',lastName: 'Flintstone'}).then(function (response) {console.log(response);}).catch(function (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) {// 兩個請求現在都執行完成}));

響應組成

response由以下幾部分信息組成

{// 服務端返回的數據data: {},// 服務端返回的狀態碼status: 200,// 服務端返回的狀態信息statusText: 'OK',// 響應頭// 所有的響應頭名稱都是小寫headers: {},// axios請求配置config: {},// 請求request: {} }

請求方法的別名

為方便起見,為所有支持的請求方法提供了別名

axios.request(config) axios.get(url[, config]) axios.delete(url[, config]) axios.head(url[, config]) axios.post(url[, data[, config]]) axios.put(url[, data[, config]]) axios.patch(url[, data[, config]])

then接收以下響應信息

axios.get('/user/12345').then(function(response) {console.log(response.data);console.log(response.status);console.log(response.statusText);console.log(response.headers);console.log(response.config);});

攔截器

在請求或響應被 then 或 catch 處理前攔截它們。

// 添加請求攔截器 axios.interceptors.request.use(function (config) {// 在發送請求之前做些什么return config;}, function (error) {// 對請求錯誤做些什么return Promise.reject(error);});// 添加響應攔截器 axios.interceptors.response.use(function (response) {// 對響應數據做點什么return response;}, function (error) {// 對響應錯誤做點什么return Promise.reject(error);});

?

與50位技術專家面對面20年技術見證,附贈技術全景圖

總結

以上是生活随笔為你收集整理的Axios的基本使用的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。