Is it possible to alter the headers of a Response
object, as returned by fetch()
?
Suppose I want to transform a response via resFn
:
self.addEventListener('fetch', function (event) {
event.respondWith(fetch(event.request).then(resFn));
});
What should resFn()
look like? One attempt:
function resFn(res) {
res = res.clone();
res.headers.set("foo", "bar");
return res;
}
Fails with TypeError: Failed to execute 'set' on 'Headers': Headers are immutable
.
(A separate question and answer explain how to alter the headers of a request. Given that the the Request
and Response
objects are surprisingly dissimilar (different properties, and their constructors take different arguments), does the same solution apply?)
This can be done by "manually" cloning the response:
where the
newResponse()
helper function is:Note that
newResponse()
returns aPromise<Response>
.