From 2d879d0592723aaa8f01cd5c3afe5a8550119e15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=BC=A0=E4=BC=A0=E9=BE=99?= Date: Sat, 24 Sep 2022 15:27:26 +0800 Subject: [PATCH] refactor: http interceptors --- src/utils/http/helpers.js | 1 - src/utils/http/index.js | 4 ++-- src/utils/http/interceptors.js | 10 +++++----- 3 files changed, 7 insertions(+), 8 deletions(-) diff --git a/src/utils/http/helpers.js b/src/utils/http/helpers.js index 450b2d7..2e45398 100644 --- a/src/utils/http/helpers.js +++ b/src/utils/http/helpers.js @@ -1,5 +1,4 @@ import { useUserStore } from '@/store' -import { isNullOrUndef } from '@/utils' export function addBaseParams(params) { if (!params.userId) { diff --git a/src/utils/http/index.js b/src/utils/http/index.js index 17f4416..6fa57ef 100644 --- a/src/utils/http/index.js +++ b/src/utils/http/index.js @@ -1,5 +1,5 @@ import axios from 'axios' -import { repReject, repResolve, reqReject, reqResolve } from './interceptors' +import { resReject, resResolve, reqReject, reqResolve } from './interceptors' export function createAxios(options = {}) { const defaultOptions = { @@ -10,7 +10,7 @@ export function createAxios(options = {}) { ...options, }) service.interceptors.request.use(reqResolve, reqReject) - service.interceptors.response.use(repResolve, repReject) + service.interceptors.response.use(resResolve, resReject) return service } diff --git a/src/utils/http/interceptors.js b/src/utils/http/interceptors.js index dff6687..ef961a5 100644 --- a/src/utils/http/interceptors.js +++ b/src/utils/http/interceptors.js @@ -25,10 +25,10 @@ export function reqReject(error) { return Promise.reject(error) } -export function repResolve(response) { +export function resResolve(response) { // TODO: 处理不同的 response.headers const { data, status, config, statusText } = response - if (response.data?.code !== 0) { + if (data?.code !== 0) { const code = data?.code ?? status /** 根据code处理对应的操作,并返回处理后的message */ @@ -36,12 +36,12 @@ export function repResolve(response) { /** 需要错误提醒 */ !config.noNeedTip && $message.error(message) - return Promise.reject({ code, message, error: response?.data }) + return Promise.reject({ code, message, error: data || response }) } return Promise.resolve(data) } -export function repReject(error) { +export function resReject(error) { if (!error || !error.response) { const code = error?.code /** 根据code处理对应的操作,并返回处理后的message */ @@ -54,5 +54,5 @@ export function repReject(error) { const message = resolveResError(code, data?.message ?? error.message) /** 需要错误提醒 */ !config?.noNeedTip && $message.error(message) - return Promise.reject({ code, message, error: error.response?.data }) + return Promise.reject({ code, message, error: error.response?.data || error.response }) }