8

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

6
  • Can you explain in detail please. I follow on this guide: developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch (Header section) Commented May 1, 2017 at 18:56
  • 1
    Does your browser fully support Fetch / Headers API? Commented May 1, 2017 at 18:57
  • 1
    I think so. I'm using latest version of Chrome on Mac. Commented May 1, 2017 at 18:57
  • 2
    Using the Chrome developers tools, does the network request include the headers? Commented May 1, 2017 at 18:58
  • 1
    oh. no. So I think something is wrong in my code. Commented May 1, 2017 at 19:00

1 Answer 1

6

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()) }); 
Sign up to request clarification or add additional context in comments.

3 Comments

I have set that option on server (I'm using rails), but no work. Moreover, I think request header that I saw in chrome doesn't depend on server (because it has been sent before come server).
@TrầnKimDự, I did some more testing on this, try changing the mode of the request to either cors, or same-origin. When I change it to either one of those, I can see the headers in the network tab in Chrome.
thanks so much. changing from "no-cors" to "cors" works for me. Also I need to do 2 things: 1. change on server (as your answer) 2. change from "no-cors" to "cors".

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.