O
O
Oleg Vavilov2016-12-02 12:22:26
JavaScript
Oleg Vavilov, 2016-12-02 12:22:26

Why doesn't the fetch method set the headers of the request?

React application fails to set headers for fetch request. I'm trying to do Basic Auth. And if I put

credentials: 'include'
then an authorization window appears in the browser window
Code
let
      headers = new Headers({
        'Content-Type': 'application/json',
        'Authorization': `Basic ${btoa('****:*****')}`
      });

    fetch(url, {
      headers: headers,
      mode: 'no-cors',
      credentials: 'include',
    })
      .then(response => {
        console.log(headers.get('Authorization')); // В консоль выводит то что должно быть в headers

        if (response.status >= 200 && response.status < 300) {
          return response.json();
        } else {
          throw response;
        }
      })
      .then(objects => dispatch({
        type: types.GET_OBJECTS_SUCCESS,
        payload: objects
      }));

And here is a screenshot from the browser
09732bb5b4894f708e69b49b52d366f0.png

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
Maxim, 2016-12-02
@maxfarseer

As for native fetch, the MDN example is as follows:

var myHeaders = new Headers();

myHeaders.append('Content-Type', 'text/xml');
myHeaders.get('Content-Type') // should return 'text/xml'

I am using the isomorphic-fetch library .
There are a couple of helpers for headers, looks like this:
export function httpGet(url) {
  return fetch(url, {
    headers: buildHeaders(),
  })
  .then(checkStatus)
}

I build the headers like this:
function buildHeaders() {
  const authToken = localStorage.getItem('myapp.token')
  return { ...defaultHeaders, Authorization: authToken }
}

Initially, the value of defaultHeaders is as follows
const defaultHeaders = {
  Accept: 'application/json',
  'Content-Type': 'application/json',
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question