我有一个网站,该网站具有基于Web组件的体系结构,其中每个Web组件都可以是单独的Vue应用程序,它具有自己的API层,可以通过Axios集成。我需要为来自根应用程序或Web组件应用程序的所有HTTP请求实现身份验证中间件。我不能使用Axios内置的拦截器机制,因为将有多个Axios实例。有什么办法可以使用全局JS方法吗?我知道那里有一些基于浏览器扩展的API,但这似乎不是我想要的东西。
以防万一其他人有兴趣,我已经与服务人员解决了。您可以订阅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));
});
服务工作者也能够拦截来自影子DOM的axios请求,因此它非常适合Web组件案例。
此外,Bartosz Polnik撰写了一篇不错的文章,介绍了如何使用Service Worker实现auth层。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句