Reputation: 41
I'm confused about the differences between a fetch request from the service worker vs. a fetch request from a regular script.
I added a service worker to intercept the request made by an audio element that links to an mp3 on another domain and the request fails because the preflight request is unsuccessful. However, if I make the same request from a script it looks like it is successful because no preflight request is made.
Here is an example glitch with the above issue: https://lucky-marsupial.glitch.me/
Code here: https://glitch.com/edit/#!/lucky-marsupial
Relevant code extracted below:
--index.html--
...
<audio src="https://traffic.libsyn.com/thefeed/126_thefeed.mp3?dest-id=149503" crossorigin="anonymous" controls="controls"> Your browser does not support the audio element. </audio>
...
--sw.js--
self.addEventListener('fetch', event => {
console.log('inside service worker', event.request.url)
event.respondWith(
fetch(event.request)
.then(response => {
if (response.status === 302) {
console.log("This line is never reached because preflight failed.")
}
return response
})
)
})
--equivalent fetch request--
fetch("https://traffic.libsyn.com/thefeed/126_thefeed.mp3?dest-id=149503",{mode: 'cors'})
.then(response => {
console.log("This line is reached because no preflight request is sent.")
return response
})
You made need to reload the page for the service worker to take affect and then try to play the audio and you should see the error message in the console.
Upvotes: 3
Views: 2441
Reputation: 41
I believe I've figured out the issue. I thought since the response header to the request has its content-type set to text-html
that it would automatically trigger a preflight request since it's not one of the content-type's listed here. However, the content-type only matters for preflight if it's set on the request, so the fetch in the script didn't require preflight.
However, the request in the service worker had a header other than one listed in the link above, range. Causing preflight to be required. Adding the range header, or any header other than what's listed in the link above, causes the fetch from the script to send a preflight request.
Funnily enough, when the request is made from the audio element itself, rather than from the service worker, it doesn't seem to trigger a preflight request even though you would think they'd be the same request.
Upvotes: 1