Skip to content Skip to sidebar Skip to footer

How To Alter The Headers Of A Response?

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)

Solution 1:

This can be done by "manually" cloning the response:

functionresFn(res) {
  returnnewResponse(res, function (headers) {
    headers.set("foo", "bar");
    return headers;
  });
}

where the newResponse() helper function is:

functionnewResponse(res, headerFn) {

  functioncloneHeaders() {
    var headers = newHeaders();
    for (var kv of res.headers.entries()) {
      headers.append(kv[0], kv[1]);
    }
    return headers;
  }

  var headers = headerFn ? headerFn(cloneHeaders()) : res.headers;

  returnnewPromise(function (resolve) {
    return res.blob().then(function (blob) {
      resolve(newResponse(blob, {
        status: res.status,
        statusText: res.statusText,
        headers: headers
      }));
    });
  });

}

Note that newResponse() returns a Promise<Response>.

Solution 2:

The current answer is quite verbose. You can achieve the same thing by doing the following:

const newHeaders = new Headers(initialResponse.headers)
newHeaders.set('foo', 'bar')
const newResponse = new Response(initialResponse.body, {
  headers: newHeaders
})  

The initial attempt in the question was close. When you create a headers object it isn't immutable, it only becomes immutable when set on the response object.

Post a Comment for "How To Alter The Headers Of A Response?"