我使用 service worker 拦截对安全资源的 HTTP 请求并向请求添加授权标头(如果用户已经登录)。现在,我有一个场景,服务工作者拦截一个 POST 请求以注入授权标头。但是,服务工作者没有接收到请求有效负载中的数据,因此没有请求有效负载(参见屏幕截图 2)。因此,nodejs 中的后端验证逻辑失败,因为没有接收到有效负载数据。理想情况下,除了授权标头之外,后端代码还应该接收有效负载数据以保存在数据库中。有什么指导吗?
下面的第一个屏幕截图是带有有效负载的原始请求。第二个到服务工作者的请求没有任何请求有效负载。
这是我拦截获取请求的服务工作者代码:
self.addEventListener('fetch', (event) => {
const fetchEvent = event;
const requestProcessor = (idToken) => {
console.log('idToken in fetch '+idToken);
let req = event.request;
// For same origin https requests, append idToken to header.
if (self.location.origin == getOriginFromUrl(event.request.url) &&
(self.location.protocol == 'https:' ||
self.location.hostname == 'localhost') &&
idToken) {
// Clone headers as request headers are immutable.
const headers = new Headers();
for (let entry of req.headers.entries()) {
headers.append(entry[0], entry[1]);
}
// Add ID token to header. We can't add to Authentication header as it
// will break HTTP basic authentication.
headers.append('Authorization', 'Bearer ' + idToken);
try {
req = new Request(req.url, {
method: req.method,
headers: headers,
mode: 'same-origin',
credentials: req.credentials,
cache: req.cache,
redirect: req.redirect,
referrer: req.referrer,
body: req.body,
bodyUsed: req.bodyUsed,
context: req.context
});
} catch (e) {
console.error('failed to prepare new header '+ e);
// This will fail for CORS requests. We just continue with the
// fetch caching logic below and do not pass the ID token.
}
}
return fetch(req);
};
// Try to fetch the resource first after checking for the ID token.
// getIdToken() returns valid idtoken for logged in user.
event.respondWith(getIdToken().then(requestProcessor, requestProcessor));
});
问候, 桑托什