React fetch has error fetch was blocked by CORS policy [duplicate]

浪尽此生 提交于 2019-12-11 08:27:45

问题


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);


}

回答1:


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



来源:https://stackoverflow.com/questions/53216361/react-fetch-has-error-fetch-was-blocked-by-cors-policy

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!