Javascript Fetch API: header params not working

陌路散爱 提交于 2019-12-10 15:35:33

问题


This is my sample request:

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

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.

thanks


回答1:


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");

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

'X-Platform-Version': '1'

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


来源:https://stackoverflow.com/questions/43724668/javascript-fetch-api-header-params-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!