VUE 數據請求和響應(axios)

1. 概述

1.1 簡介

  axios是一個基於Promise(本機支持ES6 Promise實現) 的HTTP庫,用於瀏覽器和 nodejs 的 HTTP 客戶端。具備如下特徵:vue

    • 從瀏覽器中建立 XMLHttpRequests
      • XMLHttpRequest對象用於在後臺與服務器交換數據,可作到在不從新加載頁面的狀況下更新網頁,在頁面已加載後從服務器請求數據或接收數據,在後臺向服務器發送數據。全部的瀏覽器都支持XMLHttpRequest對象。
    • 從 node.js 建立 http 請求
      • 如get/post等
    • 支持 Promise API
      • 如promise所支持的鏈式回調,.then(res => {}).catch(err =>{})
    • 攔截請求和響應
      • 在請求以前或響應以後進行的處理,如請求以前增長統一的token標識,響應以後對公用的錯誤進行處理等。
    • 轉換請求數據和響應數據
    • 取消請求
    • 自動轉換JSON數據
    • 客戶端支持防護XSRF

1.2 引入使用

  npm install axios  進行安裝,安裝成功後 import axios from 'axios' 進行引入模塊,再對axios對象進行設置。如node

/**
 * 建立axios對象
 **/
let axiosInstance =axios.create({
  baseURL: configHttp.domain,
  withCredentials:true,
});

  備註:使用 Vue.prototype.$http = axios; 進行配置於vue項目中,在頁面中可以使用this.$http.get('xxxx').then().catch()。ios

1.3 經常使用請求配置

  1.3.1 url

  數據請求的服務器URL,此配置必須存在,不然無訪問路徑沒法進行數據請求。web

  1.3.2 method

  建立請求時使用的方法,默認get方式。有多種請求方式,如:request/get/delete/head/post/put/patch,經常使用get與post.npm

  1.3.3 baseURL

  設置一個統一的基礎路徑(如http://www.demo.com/api/),使axios的get或post中的url使用相對URL,更改訪問域名或端口號時只更改對應的baseURL值便可。json

  1.3.4 headers

  headers是即將被髮送的自定義請求頭,可設置請求的數據標識(token)或post請求的數據類型等。axios

  1.3.5 timeout

  請求超時時間,單位爲毫秒,若超過超時時間則請求中斷。0表示無超時時間。api

  1.3.6 withCredentials

  跨域請求時是否須要使用憑證,默認爲false跨域

1.4 配置的默認與自定義實例

  優先級別爲:自定義實例>全局默認值>自帶默認值promise

  1.全局默認值

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';

  2.自定義實例

// 建立實例時設置配置的默認值
var instance = axios.create({
  baseURL: 'https://api.example.com'
});

// 在實例已建立後修改默認值
instance.defaults.headers.common['Authorization'] = AUTH_TOKEN;

  備註:也可在請求攔截中進行設置對應的配置。

1.5 攔截器

  在請求或響應被 then 或 catch 處理前攔截他們,分爲請求攔截器和響應攔截器

    • 請求攔截器(interceptors.request)是指能夠攔截每次或指定HTTP請求,並可修改配置項。
    • 響應攔截器()能夠攔截每次HTTP請求對應的響應,並可修改返回結果項。

  示意圖

  

  通常在請求攔截器中增長標識token或其餘請求配置,在響應攔截器中對統一錯誤或狀態碼進行處理(跳轉統一頁面如登陸)

// 添加請求攔截器
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);
  });

2. 實例

 2.1 axios配置

  備註:在headers.post['Content-Type']不爲application/json時,傳遞post參數時需使用querystring中的querystring.stringify對參數進行格式化處理。

import axios from 'axios'
import configHttp from '../../configHttp'

/**
 * 建立axios對象
 **/
let axiosInstance =axios.create({
  baseURL: configHttp.domain,
  withCredentials:true,
});

/**
 * 訪問請求攔截(在請求前處理)
 **/
axiosInstance.interceptors.request.use(
  function (config) {
    config.headers.common['Platform'] = 'web';
    return config;
  },
  function (error) {
    return Promise.reject(error)
  }
);

/**
 * 響應請求攔截(在響應前處理)
 **/
axiosInstance.interceptors.response.use(
  function (response) {
    return response;
  },
  function (error) {
    if(error.response){
      let status=error.response.status;
      switch (status) {
        case 401:
            // 跳轉至login
          break;
      }
    }
    //處理報錯 記錄日誌
    if (error !== undefined) {
      console.log(error);
    }

  }
);
/**
 * http請求響應處理函數
 **/
let httpResponseHandle = function(){
  let self = this;
  let res = self.res;
  if (res.code == '0') {
    self.successCallback && self.successCallback(res);
  } else if (res.code == 'C00004' || res.code =='C00002') {
    // 清除token
    // 跳轉至login
  } else {
    // 統一錯誤彈出
    self.failCallback && self.failCallback(res);
  }
};

let http= {
  /**
   * 以get方式請求獲取JSON數據
   * @param {Object} opts 配置項,能夠包含如下成員:
   * @param {String} opts.url 請求地址
   * @param {Object} opts.params 附加的請求參數
   * @param {Function} opts.successCallback 成功的回調函數
   * @param {Function} opts.failCallback 失敗的回調函數
   * **/
  get: function (opts) {
    axiosInstance
      .get(opts.url, {params: opts.params})
      .then(function (res) {
        opts.res = res.data;
        httpResponseHandle.call(opts);
      })
      .catch(function (err) {
        if (err.response) {
          if (err.response.data) {
            opts.res = err.response.data;
            httpResponseHandle.call(opts);
          } else {
            // 統一錯誤彈出
          }
        }
      });
  },

  /**
   * 以post方式請求獲取JSON數據
   * @param {Object} opts 配置項,能夠包含如下成員:
   * @param {String} opts.url 請求地址
   * @param {Object} opts.params 附加的請求參數
   * @param {Function} opts.successCallback 成功的回調函數
   * @param {Function} opts.failCallback 失敗的回調函數
   * **/
  post: function (opts) {
    axiosInstance
      .post(opts.url, opts.params)
      .then(function (res) {
        opts.res = res.data;
        httpResponseHandle.call(opts);
      })
      .catch(function (err) {
        if (err.response) {
          if (err.response.data) {
            opts.res = err.response.data;
            httpResponseHandle.call(opts);
          } else {
            // 統一錯誤彈出
          }
        }
      });
  }
};

export default http;

 2.2 實例調用

  在Vue中使用prototype進行設置,不能使用use設置。

  1.main.js中直接寫入

import http from '@/common/js/http.js';
Vue.prototype.$http = http;

  2.其餘引入

import Vue from 'vue'
import axios from '../common/js/http.js'

Vue.prototype.$http = axios

 2.3 頁面使用

  vue單頁面中的methods中使用

  1.get示例

  this.$http.get({
          url: 'comm/getDataInfo',
          params: {
            param1: xxx,
            param2: '3'
          },
          successCallback: res => {
            // 數據處理
          },
          failCallback: res => {}
        });

  2.post示例

   this.$http.post({
        url: 'common/userLogin',
        params: {
          username: 'admin',
          password: '123456'
        },
        successCallback: res => {
          // 數據處理
        },
        failCallback: res => {}
      });
相關文章
相關標籤/搜索