Answer the question
In order to leave comments, you need to log in
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
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
}));
Answer the question
In order to leave comments, you need to log in
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'
export function httpGet(url) {
return fetch(url, {
headers: buildHeaders(),
})
.then(checkStatus)
}
function buildHeaders() {
const authToken = localStorage.getItem('myapp.token')
return { ...defaultHeaders, Authorization: authToken }
}
const defaultHeaders = {
Accept: 'application/json',
'Content-Type': 'application/json',
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question