Javascript 获取 API:header 参数不工作

Javascript Fetch API: header params not working

这是我的样品请求:

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())
  })

当我调试时,我看到此请求已成功发送到服务器,但服务器尚未收到 header 参数(在本例中为 Platform-VersionApp-VersionPlatform).请告诉我哪里配置错了

谢谢

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

header("Access-Control-Allow-Headers: X-Requested-With");

此外,您的自定义 headers 应以 X- 为前缀。所以你应该:

'X-Platform-Version': '1'

最后一件事,您的 mode 需要 cors

您可以看到标准 headers 正在使用以下代码发送。查看网络选项卡以查看标准请求 headers。

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