Vue通過axios與java交互,並解決跨域問題

 

1. 背景

(1) 棄vue-resource推axios

Vue.js之前是推薦使用的vue-resource,但之後尤雨溪(vue.js作者)發佈消息如下:

最近團隊討論了一下,Ajax 本身跟 Vue 並沒有什麼需要特別整合的地方,使用 fetch polyfill 或是 axios、superagent 等等都可以起到同等的效果,vue-resource 提供的價值和其維護成本相比並不划算,所以決定在不久以後取消對 vue-resource 的官方推薦。已有的用戶可以繼續使用,但以後不再把 vue-resource 作爲官方的 ajax 方案。

這裏可以去掉 vue-resource,文檔也不必翻譯了。

消息原文:https://github.com/vuefe/vuejs.org/issues/186

目前主流的 Vue 項目,都選擇 axios 來完成 ajax 請求。

(2) axios簡介

npm網站對axios做了很詳盡的介紹: 
https://www.npmjs.com/package/axios

中文可以參考之前轉載的文章《axios全攻略》

axios

Promise based HTTP client for the browser and node.js

Features: 
Make XMLHttpRequests from the browser 
Make http requests from node.js 
Supports the Promise API 
Intercept request and response 
Transform request and response data 
Cancel requests 
Automatic transforms for JSON data 
Client side support for protecting against XSRF

Browser Support: 
這裏寫圖片描述

2. 實戰

關於axios的基本情況就是這樣了,那麼如何在Vue的工程中進行使用呢?這裏給出最簡單的實例,axios還有很多高級的用法,在上文推薦的介紹中有詳細介紹。

(1) 安裝

在工程目錄下,使用命令行:

npm install axios --save-dev
  • --save-dev以省掉手動修改package.json文件的步驟。

(2) 改寫原型鏈

在main.js中引如axios。由於在其他組件中無法使用axios命令,所以需要將axios改寫爲Vue的原型屬性。

import axios from 'axios' //引入axios

Vue.prototype.$ajax=axios //修改Vue的原型屬性
  •  

(3) 在組件中使用

在組件的鉤子函數中使用,與後端API交互。

mounted(){

    //GET
    this.$ajax({
      method: 'get',
      // url:'../static/test/getInfo.json', //<---本地地址
      url: '/api/drummer/8bd17859',
    }).then(response=>{
      let _data=response.data;
      alert("hello," + _data.username);
    }).catch(function(err){
        console.log(err)
    })

    //POST
    this.$ajax({
      method: 'post',
      url: '/api/drummer',
      data:{
        code: '1234567',
        username: 'Joyce'
      }
    }).then(response=>{
        alert('post code done');
    }).catch(function(err){
        console.log(err)
    });
  }


3. 解決IE兼容問題

在上文的介紹中,我們提到了瀏覽器的兼容性。IE9+是可以支持的,但是運行項目後,卻發現不可以。爲什麼呢?

這是因爲IE整個家族都不支持promise。如何解決?

(1) 安裝es6-promise

npm install es6-proimse --save-dev
  •  

(2) 引入

main.js中引入ES6的polyfill。

import Es6Promise from 'es6-promise'

Es6Promise.polyfill();
  •  
					<link href="https://csdnimg.cn/release/phoenix/mdeditor/markdown_views-2011a91181.css" rel="stylesheet">
            </div>
								
				<script>
					(function(){
						function setArticleH(btnReadmore,posi){
							var winH = $(window).height();
							var articleBox = $("div.article_content");
							var artH = articleBox.height();
							if(artH > winH*posi){
								articleBox.css({
									'height':winH*posi+'px',
									'overflow':'hidden'
								})
								btnReadmore.click(function(){
									if(typeof window.localStorage === "object" && typeof window.csdn.anonymousUserLimit === "object"){
										if(!window.csdn.anonymousUserLimit.judgment()){
											window.csdn.anonymousUserLimit.Jumplogin();
											return false;
										}else if(!currentUserName){
											window.csdn.anonymousUserLimit.updata();
										}
									}
									
									articleBox.removeAttr("style");
									$(this).parent().remove();
								})
							}else{
								btnReadmore.parent().remove();
							}
						}
						var btnReadmore = $("#btn-readmore");
						if(btnReadmore.length>0){
							if(currentUserName){
								setArticleH(btnReadmore,3);
							}else{
								setArticleH(btnReadmore,1.2);
							}
						}
					})()
				</script>
				</article>
  •  
  •  

4. 解決跨域問題

1:服務器端設置跨域 

header(“Access-Control-Allow-Origin:*”); 

header(“Access-Control-Allow-Headers:content-type”); 

header(“Access-Control-Request-Method:GET,POST”); 

2:可以自己設置一個代理服務器,使用proxyTable 我比較推薦這種方法。 

首先在config/index.js 裏面找到proxyTable :{} ,然後在裏面加入

 "/api":{
            target: 'http://47.104.218.122:8087',
            changeOrigin: true,
            pathRewrite: {
                '^/api': '/'
            }
        }
  •  

注意這裏面 /api是你自定義的,寫成什麼都可以。target 設置你調用的接口域名和端口號。這裏理解成用‘^/api’代替target裏面的地址,後面組件中我們調接口時直接用api代替 。比如我要調用’http://47.104.218.122:8087/dictionaryType‘,直接寫‘/api/dictionaryType’即可。 
然後我們可以在main.js設置一個基礎路徑,這樣你調用接口的時候可以不寫api,直接寫/接口名稱即可。在main.js 設置 axios.defaults.baseURL=”/api”; 
然後掉接口的時候可以直接寫let _url4=”/dictionaryTypes”;這樣就比較省事。

    this.$axios.get(_url4)
                    .then(response=>{
                        alert(response);
                        alert(1);
                    })
                    .catch(error=>{
                        console.log(error);
                    })
 這個是我使用vue 的時候遇到的問題   僅作爲參考。 
  • 1
            </div>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章