Fetch request with token in Header
Solution 1
With fetch()
, you cannot send Authorization
header when the no-cors
mode is enabled.
no-cors — Prevents the method from being anything other than HEAD, GET or POST, and the headers from being anything other than simple headers.
https://developer.mozilla.org/en-US/docs/Web/API/Request/mode
What are simple headers?
Accept
Accept-Language
Content-Language
-
Content-Type
and whose value, once extracted, has a MIME type (ignoring parameters) that isapplication/x-www-form-urlencoded
,multipart/form-data
, ortext/plain
https://fetch.spec.whatwg.org/#simple-header
So your problem is in the following line:
mode: 'no-cors',
Just drop it from the fetch request and append your Authorization
header as usual.
const myHeaders = new Headers();
myHeaders.append('Content-Type', 'application/json');
myHeaders.append('Authorization', '1234abcd');
return fetch('http://localhost:8080/clients/', {
method: 'GET',
headers: myHeaders,
})
Solution 2
There are multiple methods you can set the header in the request, you can check the documentation here.
Here is updated code:
function getAllClients() {
const myHeaders = new Headers({
'Content-Type': 'application/json',
'Authorization': 'your-token'
});
return fetch('http://localhost:8080/clients', {
method: 'GET',
headers: myHeaders,
})
.then(response => {
if (response.status === 200) {
return response.json();
} else {
throw new Error('Something went wrong on api server!');
}
})
.then(response => {
console.debug(response);
}).catch(error => {
console.error(error);
});
}
getAllClients();
Solution 3
Well this is what you need :
function getAllClients() {
const myHeaders = new Headers();
/*
myHeaders.append('Content-Type', 'application/json');
since it's a get request you don't need to specify your content-type
*/
myHeaders.append('Authorization', 'Token 1234abcd');
return fetch('http://localhost:8080/clients', {
method: 'GET',
mode: 'no-cors',
headers: myHeaders,
})
.then(response => response.json())
.then((user) => {
console.log(user.name);
console.log(user.location);
})
.catch((error) => {
console.error(error);
});
}
getAllClients();
peronja
Updated on May 17, 2020Comments
-
peronja about 4 years
I need help to include token in the header when I'm doing fetch request on address 'http://localhost:8080/clients'.
Right now I'm getting this message "HTTP 403 Forbidden".
Authorization Token 1234abcd
function getAllClients() { const myHeaders = new Headers(); myHeaders.append('Content-Type', 'application/json'); return fetch('http://localhost:8080/clients', { method: 'GET', mode: 'no-cors', headers: myHeaders, }) .then(response => response.json()) .then((user) => { console.log(user.name); console.log(user.location); }) .catch((error) => { console.error(error); }); } getAllClients();
-
peronja over 6 yearsThis was very helpful, but just without "mode: 'no-cors',". Thanks Fabien