vue中axios請(qǐng)求封裝(包括處理異常響應(yīng),添加loading動(dòng)畫(huà),公共請(qǐng)求頭)

配置小貼士

封裝請(qǐng)求頭時(shí)注意一下Content-Type屬性,看后臺(tái)使用什么方式接收,如是表單形式接收需要設(shè)置為application/x-www-form-urlencoded;charset=utf-8或者multipart/form-data,此時(shí)要使用qs插件處理數(shù)據(jù)將json數(shù)據(jù)轉(zhuǎn)化為from數(shù)據(jù),方法如下:

import qs from 'qs';     // json --> form
export function post(url, data){
  return new Promise((resolve,reject) => {
    request({
      method: 'post',
      url: url,
      data: qs.stringify(data)
    }).then(res => {
      if (res.flag) {
        resolve(res)
      } else {
        Message({
          message: res.message,
          type: 'error',
          duration: 2 * 1000
        })
      }
    }).catch(err => {
      Message({
        message: '網(wǎng)絡(luò)異常',
        type: 'error',
        duration: 2 * 1000
      })
      reject(err)
    })
  })
}

axios的配置中withCredentials: true配置表示允許攜帶cookie

axios.create({
 withCredentials: true,
 baseURL: baseUrl,     // 基礎(chǔ)路徑
 timeout: 5000,        // 請(qǐng)求超時(shí), 5000毫秒
 headers: {            // 添加 header 頭信息
   // json形式傳輸
   'Content-Type': 'application/json;charset=utf-8'
 }
});

如需了解更多axios配置,點(diǎn)我


上代碼

封裝的request.js公共請(qǐng)求文件

import axios from "axios";
import { baseUrl } from "./env.js"
import router from '@/router'
import { Loading, Message } from 'element-ui'
// import qs from 'qs';     // json --> form

const request = axios.create({
 // withCredentials: true,
 baseURL: baseUrl,     // 基礎(chǔ)路徑
 timeout: 5000,        // 請(qǐng)求超時(shí), 5000毫秒
 headers: {            // 添加 header 頭信息
   // 使用時(shí)結(jié)合qs使用,將json轉(zhuǎn)化為form形式傳輸,需要解開(kāi)上面的qs的注釋
   // 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8'
   // json形式傳輸
   'Content-Type': 'application/json;charset=utf-8'
 }
});

// 加載數(shù)據(jù)時(shí),打開(kāi)和關(guān)閉動(dòng)畫(huà)特效
const loading = {
 loadingInstance: null,   // Loading 實(shí)例
 open: function() {
   // console.log('加載中', this.loadingInstance)
   if(this.loadingInstance === null) {  // 創(chuàng)建單例,防止切換路由重復(fù)加載
     // console.log('創(chuàng)建實(shí)例加載')
     this.loadingInstance = Loading.service({
       text: '拼命加載中...',
       // customClass: 'loadingClass',
       // target: '.main',   // 效果顯示區(qū)域
       background: '#fff'
     })

   }
 },

 close: function() {   // 關(guān)閉加載
   if(this.loadingInstance !== null) {
     this.loadingInstance.close()
     // console.log('結(jié)束加載')
   }
   this.loadingInstance = null
 }
}

// 請(qǐng)求攔截器
request.interceptors.request.use(
 config => {
   let _token = localStorage.getItem('token')
   if (_token) {
     config.headers['Authorization'] = _token
   }
   // 這里關(guān)閉所有的消息提示,避免重復(fù)報(bào)錯(cuò)
   Message.closeAll()
   // 打開(kāi)加載效果
   loading.open()
   return config;
 },
 err => {    // 出現(xiàn)異常
   loading.close()
   return Promise.reject(err)
 }
);

// 響應(yīng)攔截器
request.interceptors.response.use(
 res => {
   loading.close()
   const response = res.data
   if (response.code !== 200 && response.status !== 200) {
     if (response.code === 20000 || response.code === 20001) {
       Message({
         message: response.message,
         type: 'error',
         duration: 5 * 1000
       })
       // 處理異常狀態(tài)清除token跳轉(zhuǎn)回登錄頁(yè)
       localStorage.removeItem('token')
       router.replace('login')
       // return Promise.reject('error')
     } else if (response.code === 90001) {
       Message({
         message: '網(wǎng)絡(luò)異常',
         type: 'error',
         duration: 5 * 1000
       })
     } else {
       Message({
         message: response.message,
         type: 'error',
         duration: 5 * 1000
       })
     }
   }
   return response
 },
 err => {
   // 出現(xiàn)異常
   loading.close()
   return Promise.reject(err);
 }
);

export function post(url, data){
 return new Promise((resolve,reject) => {
   request({
     method: 'post',
     url: url,
     data: data
   }).then(res => {
     // 這里看項(xiàng)目情況,我這邊是用flag來(lái)判斷請(qǐng)求成功與否,雖然有code===200可以判斷,但后臺(tái)小哥哥給了這個(gè)字段,不忍心不用
     if (res.flag) {
       // 請(qǐng)求成功處理,不成功則消息提示
       resolve(res)
     } else {
       Message({
         message: res.message,
         type: 'error',
         duration: 2 * 1000
       })
     }
   }).catch(err => {
     reject(err)
   })
 })
}

export function get(url){
 return new Promise((resolve,reject) => {
   request.get(url).then(res => {
       if (res.flag) {
         resolve(res)
       } else {
         Message({
           message: res.message,
           type: 'error',
           duration: 2 * 1000
         })
       }
     }).catch(err => {
       reject(err)
     })
 })
}

封裝請(qǐng)求到這里就結(jié)束了,如果不會(huì)使用,請(qǐng)看下一篇 手摸手封裝vue中api文件,讓項(xiàng)目更容易維護(hù)

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

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

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