Javascript Fetch API:标头参数不起作用 [英] Javascript Fetch API: header params not working

查看:97
本文介绍了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())
  })

当我调试时,我看到此请求已成功发送到服务器,但服务器未收到标头参数(在这种情况下是平台版本 App-版本平台)。请告诉我哪个部分配置错误。

When I debug, I see that this request is sent successfully to server, but server hasn't received header params (in this case is Platform-Version, App-Version and Platform). Please tell me which part do I config wrong.

谢谢

推荐答案

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

You are using it correctly, but you have to tell your backend service to allow custom headers (X-). For example, in PHP:

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

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

Also, your custom headers should be prefixed with X-. So you should have:

'X-Platform-Version': '1'

最后一件事,你的模式需要 cors

And one last thing, your mode needs to be cors.

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

You can see that standard headers are being sent with the following code. take a look at the network tab to see the standard request 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())
    });

这篇关于Javascript Fetch API:标头参数不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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