Search code examples
httpcorsfetch-apipreflight

fetch API: Can't add Authorization on Request Header with Chrome


Chrome version: 57.0.2987

Actually, in older Chrome version I also have this problem. I added Authorization on Request Header with my access token,

fetch('https://example.com/endpoint', {
  method: 'GET',
  headers: {
    'Authorization': 'Bearer ' + accesstoken
  }  
})

I always get Access-Control-Allow-Headers:authorization on Response Header in Chrome Besides, My fetch is always Request Method:OPTIONS (not display GET), then Status Code is 200 OK in Chrome

But if I run the same fetch code in Firefox (ver 52.0.1 ), everything works great. I can add Authorization on Request Header correctly. It won't display Access-Control-Allow-Headers:authorization on Response Header in Firefox. It will display Authorization: Bearer accesstoken on Request header.

The server side already processed CORS for my request header..

This is a Chrome bug or my code fault? How should I do to make Authorization on Request Header correctly in Chrome?

Below image is the detail Network in Chrome dev tool: Below image is the detail Network in Chrome dev tool:

Below image is the detail Network in Firefox dev tool: enter image description here


Solution

  • As @stackdave said, browser send OPTIONS request before GET request when cross-domain ajax. Then browser will wait server response. My situation that the server didn't response, so browser just stop OPTIONS status. Server need to handle this issue, it's still CORS issue, not fetch api bug or issue.