代码之家  ›  专栏  ›  技术社区  ›  ollie314

未使用fetch api填充请求头

  •  -2
  • ollie314  · 技术社区  · 5 年前

    我正在试验一种我不懂的东西。当我尝试使用 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 对象,将删除标题。即使我正在使用 set append 方法填充头。 使用 new Headers({...}); 如前所述 here 不能解决问题。更改 mode 也不会产生变化。 折叠式 this 也失败了。

    Link to the fiddle

    因此,没有定义头(我猜也没有body)。

    enter image description here

    enter image description here

    如果有人知道这个问题,我就接受:D

    当做。

    1 回复  |  直到 5 年前
        1
  •  1
  •   Bravo    5 年前

    因为你在使用 mode: 'no-cors' 你被限制在 simple headers

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

    这就是你在非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()]);