當前位置:
首頁 > 知識 > 各大框架都實用的axios封裝,攔截器統一封裝 get ,post,put請求

各大框架都實用的axios封裝,攔截器統一封裝 get ,post,put請求

為了使項目里的介面調用起來更方便,介面歸類更加分明,需要對axios進行封裝,下面我將會講解下我在項目中對axios的封裝以及處理:

該目錄是我們的項目目錄,utils文件下的request.js是封裝axios的文件,api問下下放了各個模塊的介面文件,這樣歸類更容易區分。

各大框架都實用的axios封裝,攔截器統一封裝 get ,post,put請求

打開今日頭條,查看更多圖片

一、在request.js文件里對axios進行統一封裝

第一步先引入axios依賴,iview的提示框引入在這裡只是舉例,各位可以根據自己的項目框架引入自己的提示框

import axios from "axios";

import {Message} from "iview"; // 引入iview的message組件,為了統一封裝報錯時的提示

定義下在介面呈現各個狀態時的不同提示:

const statusDic = {

400: "操作失敗",

401: "登錄超時,請重新登錄",

403: "拒絕訪問",

404: "網路資源無法訪問",

405: "請求方法不支持",

408: "請求超時,請稍後重試",

500: "伺服器內部錯誤",

501: "服務未實現",

502: "網關錯誤",

503: "服務不可用",

504: "網關超時",

505: "HTTP版本不受支持"

}

創建axios實例,請求超時時間各位可以根據自己的實際情況設置,pc端可以稍微設置長一點,移動端可以設置稍微短一點:

// 創建axios實例

const service = axios.create({

timeout: 30000, // 請求超時時間30秒

withCredentials: true // 全局默認配置設置cookies

});

request攔截器處理:

// request攔截器

service.interceptors.request.use(config => {

config.headers = {

"Content-Type": config.contentType || "application/x-www-form-urlencoded"

}

if (

config.headers["Content-Type"] === "application/x-www-form-urlencoded" &&

!config.isFormData &&

config.method !== "get"

) {

const paramsArray = []

// 拼接參數

Object.keys(config.data).forEach(key =>

paramsArray.push(`${key}=${config.data[key]}`)

)

config.data = paramsArray.join("&")

} else if (

config.headers["Content-Type"] === "application/json" &&

config.method !== "get"

) {

config.data = JSON.stringify(config.data)

}

// 以http開頭則放過

if (config.url.indexOf("http") === 0) {

return config;

}

// 以dsb開頭向後端發送的請求,本地json文件請求頭與前端域名保持一致(以下判斷處理為我公司業務邏輯,我們公司的項目前後端分離,域名可相同也可不相同,不相同的時候需要區別載入的是json文件還是後端的介面)

let reg = /^/dsb/.*$/;

if (reg.test(config.url)) {

config.url = process.env.BASE_API + config.url;

}

return config;

}, error => Promise.reject(error));

respone攔截器處理:

// response 攔截器

axios.interceptors.response.use(

(response, config) => Promise.resolve(response),

error => {

// 前端自動放棄請求提示

if (error.code && error.code === "ECONNABORTED") {

Message.error(statusDic["408"])

return Promise.reject(error)

}

if (error.response && error.response.status) {

const {status} = error.response

if (Object.keys(statusDic).indexOf(`${status}`) !== -1) {

// 該提示框為iview框架的提示框,請自行更換自己的

Message.error(statusDic[status])

if (status == 401) {

// 登錄超時時需跳轉到登錄頁面,或者退出應用,根據業務自行補上

}

}

}

return Promise.reject(error)

}

)

統一封裝 get ,post,patch,put請求:

const AJAXS = {} // 緩存ajax用於abort

const {CancelToken} = axios

/**

* 緩存ajax對象,用來abort

* @param url

* @param ajax

*/

const addAbortAjax = (url, ajax) => {

AJAXS[url] = ajax

}

const deleteAbortAjax = url => {

delete AJAXS[url]

}

/**

* 統一封裝 get ,post,patch,put請求

*/

const ajaxMethod = ["get", "post", "patch", "put"]

const $axios = {}

ajaxMethod.forEach(method => {

$axios[method] = function(url, data = {}, formatter = noop, config = {}) {

const cache = config._cacheAjax

cache && delete config._cacheAjax

if (cache) {

config.cancelToken = new CancelToken(cancel => {

addAbortAjax(url, cancel)

})

}

const authFormatter = function(res) {

return formatter(res)

}

return new Promise((resolve, reject) => {

if (method === "get") {

config.beforeSend && config.beforeSend()

config.params = data

axios[method](`${url}?_=${Date.now()}`, config)

.then(response => {

config.complete && config.complete()

deleteAbortAjax(url)

resolve(response)

})

.catch(error => {

config.complete && config.complete()

reject(error)

deleteAbortAjax(url)

})

} else {

config.beforeSend && config.beforeSend()

axios[method](url, data, config)

.then(response => {

deleteAbortAjax(url)

config.complete && config.complete()

resolve(response)

})

.catch(error => {

config.complete && config.complete()

reject(error)

deleteAbortAjax(url)

})

}

})

}

})

最後將axios實例暴露出去:

export default service

用法:先對介面進行封裝

import _ from "lodash"

import $axios from "@/utils/request"

export default {

/**

*賬號登錄

*/

login (param, config) {

return $axios

.post("/api/auth/login", param, res => res, config)

.then(res => _.get(res, "data"))

}

}

同級新增index.js文件:

import login from "./login"

export {login}

在頁面中調用

import {login} from "@/api/login"

login.login().then(response => {

})

---------------------

作者:秋風掃落葉~

原文:https://blog.csdn.net/zmm13298329239/article/details/83656565

版權聲明:本文為博主原創文章,轉載請附上博文鏈接!

喜歡這篇文章嗎?立刻分享出去讓更多人知道吧!

本站內容充實豐富,博大精深,小編精選每日熱門資訊,隨時更新,點擊「搶先收到最新資訊」瀏覽吧!


請您繼續閱讀更多來自 程序員小新人學習 的精彩文章:

Docker的一些基本操作
微軟基於F 的 Liqui|> 量子編程語言

TAG:程序員小新人學習 |