【问题标题】:Intercept Axios request with global JS methods使用全局 JS 方法拦截 Axios 请求
【发布时间】:2020-12-28 06:22:14
【问题描述】:
我有一个基于 Web 组件架构的站点,其中每个 Web 组件可能是一个单独的 Vue 应用程序,它自己的 API 层通过 Axios 集成。我需要为来自根应用程序或 Web 组件应用程序的所有 HTTP 请求实现 Auth 中间件。我不能使用 Axios 内置的拦截器机制,因为会有多个 Axios 实例。有没有办法用全局 JS 方法做到这一点?我知道那里有some browser extension based API,但这似乎不是我要找的东西。
【问题讨论】:
标签:
vue.js
axios
xmlhttprequest
【解决方案1】:
以防万一其他人感兴趣,我已经通过服务人员解决了它。您可以订阅fetch 事件并根据您的身份验证逻辑进行响应。您的 Service Worker 代码如下所示:
self.addEventListener('fetch', async (event) => {
const isAuthorised = await checkIsAuthorized(); // your auth API layer
if (!isAuthorised) {
const response = new Response(null, {
status: 401,
statusText: 'Unauthorised',
});
event.respondWith(response);
return;
}
event.respondWith(fetch(event.request));
});
Service Worker 也能够拦截来自 shadow DOM 的 axios 请求,因此非常适合 Web 组件案例。
此外,还有一个nice article by Bartosz Polnik 介绍了使用服务工作者实现身份验证层。