0

I am trying to access an API using JavaScript. When accessing it using Postman everything works fine. I can make a GET request and it sends back the correct data. However when I try to do the same using fetch(), it either returns nothing or gives me an error (depending on the mode I am using).

<script>
    async function get_page() {
        const response = await fetch("MY_LINK", {
            method:'GET',
            mode:'cors',
            redirect:'follow'
            });
            return response;
        }
    get_page().then(data => console.log(data)).catch(err => console.log(err));
</script>

The above throws:

Access to fetch at 'MY_LINK' from origin 'null' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

If I change the mode to no-cors, I get a reply but cannot seem to find the returned message (the body attribute is null) in it, that I am seeing when I use Postman.

SomeDutchGuy
  • 2,249
  • 4
  • 16
  • 42
  • works in postman but not in browser - yes, you're right, because that's how CORS works - the server needs to allow the browser to access the response - change the **server** to do so - as for no-cors, you now know what an opaque response is ... i.e. no information can be seen – Bravo Jul 23 '21 at 06:45
  • @Bravo how is it possible that Postman is still able of giving the correct response (just wondering)? – SomeDutchGuy Jul 23 '21 at 06:50
  • 1
    I think this subject answers your question: https://stackoverflow.com/questions/36250615/cors-with-postman – Amirhossein Shahbazi Jul 23 '21 at 06:53
  • because POSTMAN isn't a browser – Bravo Jul 23 '21 at 07:07

1 Answers1

-3

In a browser, with your function, this worked:

get_page().then(response => response.json()).then(data => console.log(data)).catch(err => console.log(err));

Full code (poke api :)

async function get_page() {
        const response = await fetch('https://pokeapi.co/api/v2/pokemon/ditto', {
            method:'GET',
            mode:'cors',
            redirect:'follow'
            });
            return response;
}
        
get_page().then(response => response.json()).then(data => console.log(data)).catch(err => console.log(err));

Note about CORS:

Tested on the browser console while visiting:

so it pays to see your server code as well

This is the result of my code: enter image description here

E_net4
  • 27,810
  • 13
  • 101
  • 139
malarres
  • 2,941
  • 1
  • 21
  • 35