It seems that fetch event inside service worker isn't receiving request headers, although it is stated in MDN documentation:
You can retrieve a lot of information about each request by calling parameters of the Request object returned by the FetchEvent:
event.request.url
event.request.method
event.request.headers
event.request.body
Code for fetching resource from main thread:
fetch(`${panyConfig.base}ticket-scanner/config`, {
headers: {
'X-Nsft-Locale' : `en`,
'X-Nsft-Id': `1`,
},
}).then((response) => {
return response.json();
}).then((data) => {...})
Fetch event handler inside SW file:
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request, {cacheName : CACHE_NAME})
.then(function(response) {
if(response) {
return response;
}
console.log(event.request.headers); //Log out headers
return fetch(event.request).then(function(response){
return response;
}).catch(function(err){
console.error(err);
})
})
)
});
Logging headers for every fetch event gives me empty object:
Headers {}
This is preventing me to cache this specific request which requires only these two headers. Credentials aren't required. Am I missing something?
It seems that fetch event inside service worker isn't receiving request headers, although it is stated in MDN documentation:
You can retrieve a lot of information about each request by calling parameters of the Request object returned by the FetchEvent:
event.request.url
event.request.method
event.request.headers
event.request.body
Code for fetching resource from main thread:
fetch(`${panyConfig.base}ticket-scanner/config`, {
headers: {
'X-Nsft-Locale' : `en`,
'X-Nsft-Id': `1`,
},
}).then((response) => {
return response.json();
}).then((data) => {...})
Fetch event handler inside SW file:
self.addEventListener('fetch', function(event) {
event.respondWith(
caches.match(event.request, {cacheName : CACHE_NAME})
.then(function(response) {
if(response) {
return response;
}
console.log(event.request.headers); //Log out headers
return fetch(event.request).then(function(response){
return response;
}).catch(function(err){
console.error(err);
})
})
)
});
Logging headers for every fetch event gives me empty object:
Headers {}
This is preventing me to cache this specific request which requires only these two headers. Credentials aren't required. Am I missing something?
The Headers
interface is iterable, supports a .get()
accessor, and a .has()
existence check.
You could take advantage of any of that to read the values you care about.
const request = new Request('https://example.', {
headers: {
'x-header-1': 'header 1 value',
'x-header-2': 'header 2 value',
}
});
for (const [header, value] of request.headers) {
console.log(`${header}: ${value} (via iterator)`);
}
console.log(`'x-header-1' is ${request.headers.get('x-header-1')}`);
console.log(`'x-header-2' ${request.headers.has('x-header-2') ? 'exists' : 'does not exist'}`);