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();
You can pass HTTP headers to the fetch() request as the second parameter. For example, to pass the Bearer Token Authorization Header, call fetch() with the {headers: {Authentication: 'Bearer Token'}} parameter.
The token is a text string, included in the request header. In the request Authorization tab, select Bearer Token from the Type dropdown list. In the Token field, enter your API key value. For added security, store it in a variable and reference the variable by name.
To send a GET request with a Bearer Token authorization header, you need to make an HTTP GET request and provide your Bearer Token with the Authorization: Bearer {token} HTTP header.
We need to provide our authorization token in order to list our own repositories with this API, so let's add our Authorization header (don't forget to assign your token to const token ). const token = 'YOUR_TOKEN_HERE'; fetch('https://api.github.com/user/repos', { headers: { Authorization: `token ${token}` } }) .
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 is application/x-www-form-urlencoded
,
multipart/form-data
, or text/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,
})
Hope it helps :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With