Javascript Fetch API: header options not working

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 it, I see that this request was successfully sent to the server, but the server did not receive the header parameters (in this case Platform-Version, App-Versionand Platform). Please tell me which part I am misconfigured in.

thank

+4
source share
1 answer

You use it correctly, but you must tell your internal service to allow custom headers ( X-). For example, in PHP:

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

In addition, your custom headers must have a prefix X-. So you should have:

'X-Platform-Version': '1'

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

Source: https://habr.com/ru/post/1676076/


All Articles