我有一个基于web组件的架构的网站,其中每个web组件可能是一个单独的Vue应用程序与它自己的API层集成通过Axios。我需要实现所有HTTP请求的身份验证中间件,来自根应用程序或web组件应用程序。我不能使用Axios内置的拦截器机制,因为会有多个Axios实例。有没有一种方法可以用全局JS方法来实现?我知道外面有some browser extension based API,但这似乎不是我想要的。
发布于 2020-09-15 17:58:39
为了防止其他人感兴趣,我已经和service worker解决了这个问题。您可以订阅fetch事件,并根据您的身份验证逻辑进行响应。您的服务工作者代码将如下所示:
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还能够拦截来自影子DOM的axios请求,因此它非常适合web组件的情况。
此外,还提供了一个使用服务工作者实现身份验证层的nice article by Bartosz Polnik。
https://stackoverflow.com/questions/63818064
复制相似问题