Vue2 :axios 使用之(一)

據(jù)說vuejs2.0已經(jīng)不在維護vue-resource了,vuejs2.0 已經(jīng)使用了axios了,并且官方也推薦使用axios 。

簡介

Axios 官網(wǎng)。
axios 是一個基于Promise 用于瀏覽器和 nodejs 的 HTTP 客戶端,它本身具有以下特征:

  • 瀏覽器端發(fā)起XMLHttpRequests請求
  • Node端發(fā)起http請求
  • 支持Promise API
  • 攔截請求和響應(yīng)
  • 轉(zhuǎn)化請求和響應(yīng)(數(shù)據(jù))
  • 取消請求
  • 自動轉(zhuǎn)化json數(shù)據(jù)
  • 客戶端支持抵御XSRF(跨站請求偽造)

瀏覽器兼容性:


axios-browser-support.png

安裝

Vue項目中使用如下命令安裝:
npm install axios --save
也可以使用cdn:
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

使用

參考的git代碼庫
api/index.js 文件:

import axios from 'axios'
import QS from 'qs'

let api = axios.create({
  baseURL: 'http://www.dragonflyxd.com/api/', //接口前綴(域名)
  method: 'GET',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Accept': 'application/json'
  },
  params: {},
  timeout: 10000,
  withCredentials: false,
  responseType: 'json',
  maxContentLength: 2000,
  validateStatus: function (status) {
    return status >= 200 && status < 500
  },
  maxRedirects: 5,
  transformRequest: [data => QS.stringify(data)],
  paramsSerializer: params => QS.stringify(params),
  data: {}
})

// http request 攔截器
api.interceptors.request.use(config => {
  return config
}, error => {
  return Promise.reject(error)
})

// http response 攔截器
api.interceptors.response.use(response => {
  return response
}, error => {
  return Promise.reject(error)
})

export default api

頁面上調(diào)用:

import api from '@/api/index'

api.post('/mk_login', data)
          .then(res => {
                console.log(res.data); //后臺返回的數(shù)據(jù)
                //if(res.data.status){
                  // 登錄成功
                  //this.setUserInfo2(data);
                 // this.$router.replace('/home');
                //}
              })
              .catch(error => {
                console.log("login異常:")
                console.log(error)
              })

其他

由于IE9不支持Promise,因此需要在項目入口main.js中打個補丁,否則無法發(fā)出請求:
import 'babel-polyfill'
如上,已經(jīng)能在IE9+上發(fā)起網(wǎng)絡(luò)請求,但是IE9上有個問題:response.data為undefined,因此需要對返回的數(shù)據(jù)針對不同瀏覽器進行處理,在API.js中加入如下攔截器:

// 響應(yīng)攔截
axios.interceptors.response.use(function (response) {
  var data
  // IE9時response.data是undefined,因此需要使用response.request.responseText(Stringify后的字符串)
  if(response.data == undefined){
    data = response.request.responseText
  } else{
    data = response.data
  }
  // 判斷data不是Object時,解析成Object
  if(!(data instanceof Object)){
    data = JSON.parse(data)
  }
  return data
}, function (error) {
  return Promise.reject(error)
});

axios跨域請求問題: No 'Access-Control-Allow-Origin' header is present on the requested resource.
網(wǎng)上搜了不少資料,很多都說需要前端配置,比如下面2種方式:

  1. 代理:config/index.js: proxyTable相關(guān)設(shè)置
  2. 瀏覽器chrome裝個插件:Allow-Control-Allow-Origin 做本地開發(fā)

實際上,我這里配置了上面的也沒用,只需要后臺那邊配置就行(后臺開發(fā)人員知道的,你跟他溝通一下就行),比如下面兩種方式:

  1. Servlet,MVC都可以,Web.xml
    https://www.cnblogs.com/best/p/8202370.html
  2. Spring MVC,修改Spring 配置文件,低Spring版本不支持
    https://www.cnblogs.com/best/p/8202370.html

參考

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容