Search code examples
javascriptjsonheadercorsfetch

fetch won't let me authorize get request


I'm trying to use fetch over the broswer but it just won't work.

I tried:

fetch('https://api-2sizcg3ipa-uc.a.run.app/fats', {
headers: {'Authorization': 'Basic ' + btoa('username:password')},
mode:'no-cors'
})
.then(response => response.json())
.then(json => console.log(json));

But it gives me two errors:

GET https://api-2sizcg3ipa-uc.a.run.app/fats net::ERR_ABORTED 403

Uncaught (in promise) SyntaxError: Unexpected end of input at fetch.js:5

What am I doing wrong? I works when I do it with curl.


Solution

  • You said:

    mode:'no-cors'
    

    This makes fetch quietly ignore anything that requires permission via CORS instead of failing with an error.

    Sending Authorization headers requires permission via CORS.

    So don't say you don't want to use it.

    Do, however, say credentials: 'include' as you want to send credentials.