How to alter the headers of a Response?

后端 未结 1 1202
执笔经年
执笔经年 2020-12-19 13:04

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         


        
1条回答
  •  独厮守ぢ
    2020-12-19 13:20

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

    function resFn(res) {
      return newResponse(res, function (headers) {
        headers.set("foo", "bar");
        return headers;
      });
    }
    

    where the newResponse() helper function is:

    function newResponse(res, headerFn) {
    
      function cloneHeaders() {
        var headers = new Headers();
        for (var kv of res.headers.entries()) {
          headers.append(kv[0], kv[1]);
        }
        return headers;
      }
    
      var headers = headerFn ? headerFn(cloneHeaders()) : res.headers;
    
      return new Promise(function (resolve) {
        return res.blob().then(function (blob) {
          resolve(new Response(blob, {
            status: res.status,
            statusText: res.statusText,
            headers: headers
          }));
        });
      });
    
    }
    

    Note that newResponse() returns a Promise.

    0 讨论(0)
提交回复
热议问题