vue之交互Axios(九)

一、axios 簡介

axios 是一個基于Promise 用于瀏覽器和 nodejs 的 HTTP 客戶端,它本身具有以下特征:

1、從瀏覽器中創(chuàng)建 XMLHttpRequest
2、從 node.js 發(fā)出 http 請求
3、支持 Promise API
4、攔截請求和響應
5、轉(zhuǎn)換請求和響應數(shù)據(jù)
6、取消請求
7、自動轉(zhuǎn)換JSON數(shù)據(jù)
8、客戶端支持防止 CSRF/XSRF

二、下載安裝

//npm安裝
npm install axios --save
//cdn安裝
<script type="text/javascript"  src="axios.js"></script>

三、發(fā)送請求

<1>get 請求

axios.get('/list?id=1').then(function (res) {
    console.log(res);
}).catch(function (error) {
    console.log(error);
 });

//以上請求也可以像如下方式寫
axios.get('/user', {
    params: {
      id: 1
    }
  }).then(function (response) {
       console.log(response);
  }).catch(function (error) {
    console.log(error);
  });

<2>post請求

axios.post('/list', {
    username: 'tom',
    password: '123456'
  }).then(function (res) {
    console.log(res);
  }).catch(function (error) {
    console.log(error);
  });

<3>通用請求

   axios({
      url:"/list",
      methodl:"get",
      params:{
           id:1
      }
   }).then((res)=>{
         console.log(res)
   }).catch((error)=>{
        console.log(error)
   })

<4>并發(fā)請求

function getHomeList() {
     return axios.get('/list/1');
}
 
function getHomeData() {
    return axios.get('/list/1');
}
 
axios.all([getHomeList(),getHomeData()])
.then(axios.spread(function (acct, perms) {
    //兩個請求現(xiàn)已完成
}));

三、請求方法別名

為了方便起見,已經(jīng)為所有支持的請求方法提供了別名。

axios.request(config)
axios.get(url [,config])
axios.delete(url [,config])
axios.head(url [,config])
axios.post(url [,data [,config]])
axios.put(url [,data [,config]])
axios.patch(url [,data [,config]])

四、創(chuàng)建實例

//create創(chuàng)建一個新的實例對象
var instance = axios.create({
   url: 'http://localhost:3000',
   imeout: 3000,
   method: 'post'
});
//即可調(diào)用方法,和axios實例同
instance.get('http://localhost:3000').then(res=>{
   console.log(res);
});

五、默認配置

//全局默認配置
axios.defaults.baseURL = 'http://localhost:3000/';
axios.defaults.headers.common['Authorization'] = AUTH_TOKEN;
axios.defaults.headers.post['content-Type'] = 'appliction/x-www-form-urlencoded';
//自定義實例默認配置
//當創(chuàng)建實例的時候配置默認配置
var instance = axios.create({
    baseURL: 'http://localhost:8080/'
});
//當實例創(chuàng)建時候修改配置
instance.defaults.headers.common["Authorization"] = AUTH_TOKEN;

六、攔截器

//添加一個請求攔截器
axios.interceptors.request.use(function(config){
  //在請求發(fā)出之前進行一些操作
  return config;
},function(err){
  //Do something with request error
  return Promise.reject(error);
});
//添加一個響應攔截器
axios.interceptors.response.use(function(res){
  //在這里對返回的數(shù)據(jù)進行處理
  return res;
},function(err){
  return Promise.reject(error);
})

2.取消攔截器
var myInterceptor = axios.interceptor.request.use(function(){/*....*/});
axios.interceptors.request.eject(myInterceptor);

3.給自定義的axios實例添加攔截器
var instance = axios.create();
instance.interceptors.request.use(function(){})

七、封裝axios

import axios from 'axios'
import qs from 'qs'
import store from 'store/index'
import router from '../router'
import { Indicator, Toast } from 'mint-ui'
axios.defaults.timeout = 100000 // 請求超時時間
axios.defaults.baseURL = process.env.VUE_APP_BASE_API
// axios.defaults.baseURL = 'http://119.3.219.52:8080/firework'
// axios.defaults.headers.post['Content-Type'] =
    'application/x-www-form-urlencoded;charset=UTF-8' // post請求頭的設置
// axios 請求攔截器
axios.interceptors.request.use(
    config => {
        // 可在此設置要發(fā)送的token
        let token = store.getters['login/token'];
        token && (config.headers.token = token)
        Indicator.open('數(shù)據(jù)加載中')
        return config
    },
    error => {
        return Promise.error(error)
    }
)
// axios respone攔截器
axios.interceptors.response.use(
    response => {
        // 如果返回的狀態(tài)碼為200,說明接口請求成功,可以正常拿到數(shù)據(jù)
        // 否則的話拋出錯誤 結合自身業(yè)務和后臺返回的接口狀態(tài)約定寫respone攔截器
        Indicator.close()
        if (response.status === 200 && response.data.code === 0) {
            return Promise.resolve(response)
        } else {
            Toast({
                message: response.data.msg,
                position: 'middle',
                duration: 2000
            });
            return Promise.reject(response)
        }
    },
    error => {
        Indicator.close()
        const responseCode = error.response.status
        switch (responseCode) {
            // 401:未登錄
            case 401:
                break
            // 404請求不存在
            case 404:
                Toast({
                    message: '網(wǎng)絡請求不存在',
                    position: 'middle',
                    duration: 2000
                });
                break
            default:
                Toast({
                    message: error.response.data.message,
                    position: 'middle',
                    duration: 2000
                });
        }
        return Promise.reject(error.response)
    }
)
/**
 * 封裝get方法,對應get請求
 * @param {String} url [請求的url地址]
 * @param {Object} params [請求時攜帶的參數(shù)]
 */
function get (url, params = {}) {
    return new Promise((resolve, reject) => {
        axios
            .get(url, {
                params: params
            })
            .then(res => {
                resolve(res.data)
            })
            .catch(err => {
                reject(err.data)
            })
    })
    // 或者return axios.get();
}
/**
 * post方法,對應post請求
 * @param {String} url [請求的url地址]
 * @param {Object} params [請求時攜帶的參數(shù)]
 */
function post (url, params) {
    return new Promise((resolve, reject) => {
        axios
            .post(url, qs.stringify(params))
            .then(res => {
                // console.log(res)
                if(res.data.code==100){
                    store.commit('login/LOGOUT',{
                        $router:router,
                    })
                }
                resolve(res.data)
            })
            .catch(err => {
                resolve(err.data)
            })
    })
    //  或者return axios.post();
}
export { get, post }

如果感覺有幫助,請留下寶貴的贊,還可以贊賞一下?。?!

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

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

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