1. 程式人生 > >vue全域性配置axios

vue全域性配置axios

由於尤雨溪之前在微博釋出訊息,不再繼續維護vue-resource,並推薦大家開始使用 axios 。所以在現在的專案中就試著使用了axios

Axios 是一個基於 promise 的 HTTP 庫,可以用在瀏覽器和 node.js 中。使用起來也比較方便。

安裝

使用npm:

$ npm install axios

使用bower:

$ bower install axios

使用cdn:

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

配置使用

安裝完成就可以使用了,這裡我們就對Vue專案說一下。
在開發時,我們可以使用config進行axios的配置,還可以做一些請求攔截等。
首先,我們可以在src目錄下建立untils資料夾來存放我們的配置檔案。

這裡寫圖片描述

配置如下:

'use strict'

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

axios.interceptors.request.use(config => {    // 這裡的config包含每次請求的內容
    // 判斷localStorage中是否存在api_token
    if (localStorage.getItem('api_token')) {
        //  存在將api_token寫入 request header
        config.headers.apiToken = `${localStorage.getItem('api_token'
)}`; } return config; }, err => { return Promise.reject(err); }); axios.interceptors.response.use(response => { return response }, error => { return Promise.resolve(error.response) }); function checkStatus (response) { // 如果http狀態碼正常,則直接返回資料 if (response && (response.status === 200
|| response.status === 304 || response.status === 400)) { return response } // 異常狀態下,把錯誤資訊返回去 return { status: -404, msg: '網路異常' } } function checkCode (res) { // 如果code異常(這裡已經包括網路錯誤,伺服器錯誤,後端丟擲的錯誤),可以彈出一個錯誤提示,告訴使用者 if (res.status === -404) { alert(res.msg) } if (res.data && (!res.data.success)) { // alert(res.data.error_msg) } return res } // 請求方式的配置 export default { post (url, data) { // post return axios({ method: 'post', baseURL: '/backapis', url, data: qs.stringify(data), timeout: 5000, headers: { 'X-Requested-With': 'XMLHttpRequest', 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' } }).then( (response) => { return checkStatus(response) } ).then( (res) => { return checkCode(res) } ) }, get (url, params) { // get return axios({ method: 'get', baseURL: '/backapis', url, params, // get 請求時帶的引數 timeout: 5000, headers: { 'X-Requested-With': 'XMLHttpRequest' } }).then( (response) => { return checkStatus(response) } ).then( (res) => { return checkCode(res) } ) } }

這裡我們還可以配置攔截器,在處理 then 或 catch 之前攔截請求和響應。因為專案中後端同事處理過了,這裡我就不配置了 哈哈~~~

接下來,在mainjs中引用就可以使用了

import axios from './untils/http';

//  這樣就可以通過$axios發起請求了(個人使用喜好)
Vue.prototype.$axios = axios;  

具體如下:

這裡寫圖片描述