Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fetch event not receiving request headers

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(`${companyConfig.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?

like image 979
Ivan Pandžić Avatar asked Nov 16 '17 16:11

Ivan Pandžić


People also ask

How do I get response headers in Fetch?

We then fetch this request using fetch() , extract a blob from the response using Response. blob , create an object URL out of it using URL. createObjectURL , and display this in an <img> . Note that at the top of the fetch() block, we log the response headers to the console.

How do I view response headers?

To view the request or response HTTP headers in Google Chrome, take the following steps : In Chrome, visit a URL, right click , select Inspect to open the developer tools. Select Network tab. Reload the page, select any HTTP request on the left panel, and the HTTP headers will be displayed on the right panel.


1 Answers

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.com', {
  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'}`);
like image 193
Jeff Posnick Avatar answered Oct 27 '22 01:10

Jeff Posnick