如何更改请求的标头?

时间:2016-02-15 23:25:43

标签: javascript service-worker

是否可以更改Request事件收到的fetch对象的标头?

两次尝试:

  1. 修改现有标头:

    self.addEventListener('fetch', function (event) {
      event.request.headers.set("foo", "bar");
      event.respondWith(fetch(event.request));
    });
    

    Failed to execute 'set' on 'Headers': Headers are immutable失败。

  2. 创建新的Request对象:

    self.addEventListener('fetch', function (event) {
      var req = new Request(event.request, {
        headers: { "foo": "bar" }
      });
      event.respondWith(fetch(req));
    });
    

    Failed to construct 'Request': Cannot construct a Request with a Request whose mode is 'navigate' and a non-empty RequestInit.

  3. 失败

    (另见How to alter the headers of a Response?

3 个答案:

答案 0 :(得分:11)

只要您设置了所有选项,就可以创建新的请求对象:

// request is event.request sent by browser here 
var req = new Request(request.url, {
    method: request.method,
    headers: request.headers,
    mode: 'same-origin', // need to set this properly
    credentials: request.credentials,
    redirect: 'manual'   // let browser handle redirects
});

如果是mode(这就是您获得例外的原因),则无法使用原始navigate,并且您可能希望将重定向传递回浏览器以允许其更改其网址而不是让fetch处理它。

确保您没有在GET请求上设置正文 - fetch不喜欢它,但浏览器有时会在响应POST请求的重定向时与正文生成GET请求。 fetch不喜欢它。

答案 1 :(得分:5)

您是否尝试过类似于您提到的问题(How to alter the headers of a Response?)的解决方案?

在Service Worker Cookbook中,我们手动复制Request对象以将它们存储在IndexedDB(https://serviceworke.rs/request-deferrer_service-worker_doc.html)中。出于不同的原因(我们希望将它们存储在缓存中,但由于https://github.com/slightlyoff/ServiceWorker/issues/693我们无法存储POST请求),但它应该适用于您想要执行的操作好。

// Serialize is a little bit convolved due to headers is not a simple object.
function serialize(request) {
  var headers = {};
  // `for(... of ...)` is ES6 notation but current browsers supporting SW, support this
  // notation as well and this is the only way of retrieving all the headers.
  for (var entry of request.headers.entries()) {
    headers[entry[0]] = entry[1];
  }
  var serialized = {
    url: request.url,
    headers: headers,
    method: request.method,
    mode: request.mode,
    credentials: request.credentials,
    cache: request.cache,
    redirect: request.redirect,
    referrer: request.referrer
  };



  // Only if method is not `GET` or `HEAD` is the request allowed to have body.
  if (request.method !== 'GET' && request.method !== 'HEAD') {
    return request.clone().text().then(function(body) {
      serialized.body = body;
      return Promise.resolve(serialized);
    });
  }
  return Promise.resolve(serialized);
}

// Compared, deserialize is pretty simple.
function deserialize(data) {
  return Promise.resolve(new Request(data.url, data));
}

答案 2 :(得分:0)

您可以基于原始请求创建一个新请求并覆盖标题:

new Request(originalRequest, {
  headers: {
    ...originalRequest.headers,
    foo: 'bar'
  }
})