【问题标题】:Request header are not filled using Fetch API请求标头未使用 Fetch API 填充
【发布时间】:2019-10-26 18:43:07
【问题描述】:

我正在尝试一些我不理解的东西。当我尝试使用Fetch API 设置请求的标头时,实际上没有定义任何标头。

这是一段代码和一个小提琴的链接,以便能够重现。

function createRequest(type, url, payload) {
  const options = { headers: {
    "Content-Type": "application/json",
    "x-request-id": '...',
    "x-sender-id": "mysender"
  },
  method: 'POST',
  body: JSON.stringify(payload),
  mode: 'no-cors',
  cache: 'no-cache'
  };
  return new Request(url, options);
}

// -----------------------------
// a simple test
const request = createRequest('post', '/check', {test: 'where are my headers?'});

当我使用Headers 对象创建标头时,标头会被丢弃。即使我使用setappend 方法来填充标题也是如此。 使用new Headers({...}); 所述here 并不能解决问题。更改 mode 也不会产生任何变化。 关注this 也会失败。

Link to the fiddle

因此,没有定义任何标题(我猜也没有定义正文)。

如果有人对此问题有任何想法,我会接受:D

问候。

【问题讨论】:

    标签: javascript fetch


    【解决方案1】:

    由于您使用的是mode: 'no-cors',因此您只能使用simple headers

    • 接受
    • 接受语言
    • 内容语言
    • 内容类型

    这就是你在 no-cors 模式下允许的所有标题

    来源:documentation

    下面,第一个请求是 no-cors 模式,第二个是同源模式(不过,这也可以是 cors 并且工作方式相同)

    // Code goes here
    
    function createRequest(type, url, payload, corsmode) {
      const options = {
        headers: {
          "Content-Type": "application/json",
          "x-request-id": '...',
          "x-sender-id": "mysender"
        },
        method: 'POST',
        body: JSON.stringify(payload),
        mode: corsmode,
        cache: 'no-cache'
      };
      return new Request(url, options);
    }
    
    // -----------------------------
    // a simple test
    const request = createRequest('post', '/check', {
      test: 'where are my headers?'
    }, 'no-cors');
    
    
    console.log([...request.headers.entries()]);
    
    const request2 = createRequest('post', '/check', {
      test: 'where are my headers?'
    }, 'same-origin');
    
    console.log([...request2.headers.entries()]);

    【讨论】:

    • @ollie314 - 我添加了一个代码 sn-p 来显示差异并展示如何将标头记录到控制台
    猜你喜欢
    • 1970-01-01
    • 2020-03-12
    • 2017-01-24
    • 2017-08-05
    • 2021-01-16
    • 2017-07-13
    • 1970-01-01
    • 2018-05-01
    • 2017-07-11
    相关资源
    最近更新 更多