From b761878e5480a4ad1d0a34b86f05791c5c5263d3 Mon Sep 17 00:00:00 2001 From: LingandRX Date: Mon, 23 Dec 2024 21:53:18 +0800 Subject: [PATCH] add fetchInterceptor.js --- src/main.js | 1 + src/utils/fetchInterceptor.js | 40 +++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 src/utils/fetchInterceptor.js diff --git a/src/main.js b/src/main.js index 4317401..70e2e34 100644 --- a/src/main.js +++ b/src/main.js @@ -7,6 +7,7 @@ import App from './App.vue' import router from './router' import Antd from 'ant-design-vue' import 'ant-design-vue/dist/reset.css' +import './utils/fetchInterceptor.js' const app = createApp(App) diff --git a/src/utils/fetchInterceptor.js b/src/utils/fetchInterceptor.js new file mode 100644 index 0000000..1d53096 --- /dev/null +++ b/src/utils/fetchInterceptor.js @@ -0,0 +1,40 @@ +const originalFetch = window.fetch + +window.fetch = async (input, init = {}) => { + console.log('拦截请求:', input, init) + + // 确保 init 对象初始化 + init = init || {} + init.headers = { + ...init.headers, // 合并已有的 headers + Authorization: 'Bearer YOUR_TOKEN' // 添加默认授权头 + } + + if (init && !init.headers) { + init.headers = {} + } + + init.headers = { + ...init.headers, + 'x-token': '123456' + } + + const response = await originalFetch(input, init) + + const clonedResponse = response.clone() + + const data = await clonedResponse.json() + + console.log('拦截响应:', data) + + const modifiedData = { + ...data, + intercepted: 'true' + } + + return new Response(JSON.stringify(modifiedData), { + status: response.status, + statusText: response.statusText, + headers: response.headers + }) +}