Skip to content
Advertisement

Text response is empty when using fetch

The following code:

JavaScript

is outputting:

JavaScript

If I use curl:

JavaScript

I get a token in text form back (length != 0).

And if I output the response header via:

JavaScript

I get:

JavaScript

Why am I getting no text via fetch?

Advertisement

Answer

Remove mode: 'no-cors'.

When you use no-cors mode, you’re explicitly specifying that you want an “opaque response”.

Your script can’t access any properties of an opaque response—instead essentially all you can do is cache it. no-cors mode is basically useful only when doing caching with Service Workers.

If the reason you have your script using no-cors mode is because cross-origin requests to the server otherwise won’t work, the right solution is either to update the server-side code to send the Access-Control-Allow-Origin response header and other CORS headers—if you have access to the server do to that—or else, use a proxy like https://cors-anywhere.herokuapp.com/.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement