Javascript Fetch API:标头参数不起作用

Trầ*_* Dự 4 javascript fetch-api

这是我的样品请求:

var header = new Headers({
  'Platform-Version': 1,
  'App-Version': 1,
  'Platform': 'FrontEnd'
});

var myInit = {
  method : 'GET',
  headers: header,
  mode   : 'no-cors',
  cache  : 'default'
}

fetch('http://localhost:3000/api/front_end/v1/login', myInit)
  .then(res => {
    console.log(res.text())
  })
Run Code Online (Sandbox Code Playgroud)

当我调试时,我看到此请求已成功发送到服务器,但服务器尚未收到标头参数(在本例中为Platform-Version,App-VersionPlatform).请告诉我哪个部分配置错误.

谢谢

Kev*_*Bot 5

您正确使用它,但您必须告诉您的后端服务允许自定义标头(X-).例如,在PHP中:

header("Access-Control-Allow-Headers: X-Requested-With");
Run Code Online (Sandbox Code Playgroud)

此外,您的自定义标头应该以前缀为前缀X-.所以你应该:

'X-Platform-Version': '1'
Run Code Online (Sandbox Code Playgroud)

最后一件事,你的mode需要cors.

您可以看到使用以下代码发送标准标头.查看网络选项卡以查看标准请求标头.

var header = new Headers();

// Your server does not currently allow this one
header.append('X-Platform-Version', 1);

// You will see this one in the log in the network tab
header.append("Content-Type", "text/plain");

var myInit = {
    method: 'GET',
    headers: header,
    mode: 'cors',
    cache: 'default'
}

fetch('http://localhost:3000/api/front_end/v1/login', myInit)
    .then(res => {
        console.log(res.text())
    });
Run Code Online (Sandbox Code Playgroud)

  • @TrầnKimDự,我对此做了更多测试,尝试将请求模式更改为“cors”或“same-origin”。当我将其更改为其中之一时,我可以在 Chrome 的网络选项卡中看到标头。 (2认同)