【发布时间】:2019-04-12 11:17:29
【问题描述】:
我尝试让登录按钮单击调用 fetch REST 调用。
但是,问题是提取失败,并在 Javascript 控制台中显示此错误消息。
// 从源获取的访问已被 CORS 策略阻止:请求的资源上不存在“Access-Control-Allow-Origin”标头 // 如果不透明满足您的需要,请将请求模式设置为“no-cors”以获取禁用 CORS 的资源。 // 异常获取失败。
为什么会发生这种情况,为什么我不能通过 React 中的按钮单击调用 REST 调用?
私有句柄Login = () => {
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);
}
【问题讨论】:
-
在stackoverflow.com/questions/43871637/…查看答案的如何使用 CORS 代理来解决“No Access-Control-Allow-Origin 标头”问题部分