fetch() does not send headers?

The same-origin policy restricts the kinds of requests that a Web page can send to resources from another origin.

In the no-cors mode, the browser is limited to sending “simple” requests — those with safelisted methods and safelisted headers only.

To send a cross-origin request with headers like Authorization and X-My-Custom-Header, you have to drop the no-cors mode and support preflight requests (OPTIONS).

The distinction between “simple” and “non-simple” requests is for historical reasons. Web pages could always perform some cross-origin requests through various means (such as creating and submitting a form), so when Web browsers introduced a principled means of sending cross-origin requests (cross-origin resource sharing, or CORS), it was decided that such “simple” requests could be exempt from the preflight OPTIONS check.


I also had this same issue. I resolved it by removing 'no-cors' from javascript and adding the following in server side spring boot.

public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
        protected void configure(HttpSecurity httpSecurity) throws Exception {
             .antMatchers(HttpMethod.OPTIONS, "/**").permitAll()

        }
    }

Firstly : Use an object instead of new Headers(..):

fetch('www.example.net', {
  method: 'POST',
  headers: {
    'Content-Type': 'text/plain',
    'X-My-Custom-Header': 'value-v',
    'Authorization': 'Bearer ' + token,
  }
});

Secondly : Good to know, headers are lowercased by fetch!!

Thirdly : no-cors mode limits the use of headers to this white list :

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type and whose value is ( application/x-www-form-urlencoded, multipart/form-data, text/plain )

That's why only your Content-Type header is sent and not X-My-Custom-Header or Authorization.


Can you try this?

fetch(serverEndpoint, {  
  credentials: 'include'  
})

Ref. https://developers.google.com/web/updates/2015/03/introduction-to-fetch#sending_credentials_with_a_fetch_request