4

I tried to have a login button click call a fetch REST call.

However, the problem is that the fetch fails, with this error message in the Javascript console.

// Access to fetch from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource // If an opaque serves your need set the requests mode to 'no-cors' to fetch the resource with CORS disabled. // Exception Failed to Fetch.

Why is this happening, and why can't I call a REST call from a Button click in React?

private handleLogin = () => {

    console.log("button submit");

    // Access to fetch from origin has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource
    // If an opaque serves your need set the requests mode to 'no-cors' to fetch the resource with CORS disabled.
    // Exception Failed to Fetch.
    fetch('https://gturnquist-quoters.cfapps.io/api/random')
    .then((res) => {
        if (res.status >= 400) {
            throw new Error("Bad response from server");
        }
        return res.json();
    })
    .then((stories) => {
        console.log(stories);
    });


    this.props.login(this.state);


}
joe the coder
  • 429
  • 2
  • 5
  • 13
  • See the *How to use a CORS proxy to get around “No Access-Control-Allow-Origin header” problems* section of the answer at https://stackoverflow.com/questions/43871637/no-access-control-allow-origin-header-is-present-on-the-requested-resource-whe/43881141#43881141 – sideshowbarker Nov 08 '18 at 21:36

1 Answers1

0

The API you're trying to call doesn't allow to be called from a browser via AJAX. It needs to set specific headers to indicate which ajax requests are allowed.

More here: https://gturnquist-quoters.cfapps.io/api/random

Daniel Rothig
  • 621
  • 2
  • 10