在Vue中如何使用axios跨域訪問數據(轉)
最近在項目中需要用到axios,所以就惡補一下這個axios到底是什麽東東。越來它是vue-resource的替代品,官網也說了,以後都用axios,
vue-resource不在維護。那麽這個axios怎麽用呢,上網搜索了一大堆,基本上都是雷同,我也不知道那些作者有沒有在本地測試過。至少我按照網上的做法,總不能成功。經過幾天的奮鬥,我終於把它搞清楚了,為了不讓其他的小夥伴們走彎路,我把我在實際操作中的例子分享給大家,希望對大家有用。
一、安裝axios
老規矩,要想使用axios,我們得安裝它,安裝方式:npm install axios
二、客戶端使用方式
先來看看網上的答案,如圖所示,我已經在圖上標識過了,這種做法是錯誤的。
![技術分享](http://upload-images.jianshu.io/upload_images/6271831-d4ea58f90f1bf28a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
正確的做法是去掉post,如圖所示:
![技術分享](http://upload-images.jianshu.io/upload_images/6271831-74e86cca98a82cd4.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![技術分享](http://upload-images.jianshu.io/upload_images/6271831-0b69aee96a53cbf3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
三、服務器端設置
雖然客戶端跨域設置好了,但是你還是不能訪問接口數據,必須在服務器端設置header屬性,如圖所示:
![技術分享](http://upload-images.jianshu.io/upload_images/6271831-9d8da41b1b7972ca.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
四、axios方法封裝
一般情況下,我們會用到的方法有:GET,POST,PUT,PATCH,封裝方法如下:
![技術分享](http://upload-images.jianshu.io/upload_images/6271831-d88d73da436437d9.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
![技術分享](http://upload-images.jianshu.io/upload_images/6271831-f3849369bc0cc0c7.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
五、封裝後的方法的使用
1、在main.js文件裏引用之前寫好的文件,我的命名為http.js
![技術分享](http://upload-images.jianshu.io/upload_images/6271831-c45725ef5d259465.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
2、在需要的地方之間調用,如圖所示:
![技術分享](http://upload-images.jianshu.io/upload_images/6271831-02f3810c781a760a.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)
說明:
GET調用方法如下,其中url是接口地址
this.$get(url).then((res) {
//代碼
});
POST調用方法如下,其中url是接口地址,data是請求的數據。
this.$post(url,data).then({
//代碼
});
PATCH調用方法如下,其中url是接口地址,data是請求的數據
this.$patch(url,data).then({
//代碼
});
PUT調用方法如下,其中url是接口地址,data是請求的數據
this.$put(url,data).then({
//代碼
});
看了以上內容,是不是很簡單,其實也沒啥的,但是就是這個問題卡了我好久,在看看網上的答案,真的是不堪一擊。問題解決了,內心真的好激動啊 O(∩_∩)O哈!
作者:陳楠酒肆
鏈接:http://www.jianshu.com/p/3b5e453f54f5
來源:簡書
著作權歸作者所有。商業轉載請聯系作者獲得授權,非商業轉載請註明出處。
在Vue中如何使用axios跨域訪問數據(轉)