如何更改请求的标头? [英] How to alter the headers of a Request?

查看:294
本文介绍了如何更改请求的标头?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以更改 请求 对象API / FetchEventrel =noreferrer> fetch 事件?

Is it possible to alter the headers of the Request object that is received by the fetch event?

两次尝试:


  1. 修改现有标题:

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

失败>'Headers'上执行'set'失败:标题是不可变的

创建新的请求对象:

Create new Request object:

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

失败构建请求失败:无法构建具有请求的请求请求其模式为导航且非空的RequestInit。

(参见还如何更改响应的标题?

推荐答案

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

Creating a new request object works as long as you set all the options:

// 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
});

你不能使用原来的模式如果它是导航(这就是你获得异常的原因)并且你可能想要将重定向传递回浏览器以让它更改其URL而不是让获取处理它。

You cannot use the original mode if it is navigate (that's why you were getting an exception) and you probably want to pass redirection back to browser to let it change its URL instead of letting fetch handle it.

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

Make sure you don't set body on GET requests - fetch does not like it, but browsers sometimes generate GET requests with the body when responding to redirects from POST requests. fetch does not like it.

这篇关于如何更改请求的标头?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆