【发布时间】:2019-09-05 15:08:22
【问题描述】:
每当我尝试使用 React 中的“获取”方法从我的 REST API 获取数据时,我都会收到“已被 CORS 策略阻止:没有“访问控制允许来源”错误。我做了研究,发现它可以用标题解决?问题是我是新来的反应和使用 API,所以我不太确定它们是什么。带有标题的 componendeDidMiunt 可能是什么样的?
constructor(props) {
super(props)
this.state = {
items: [],
isLoaded: false
}
}
componentDidMount() {
fetch('http://localhost:8080/seniorproject/getUserCourses/1')
.then(res => res.json())
.then(json => {
this.setState({
isLoaded: true,
items: json
})
});
}
render() {
var {items, isLoaded } = this.state;
if(!isLoaded) {
return (
<div>
...Loading
</div>
)
} else {
return (
<div className="App">
Data has been loaded..
</div>
);
}
}
}
【问题讨论】:
-
欢迎来到 Stack Overflow thechans7!是的,你是对的,CORS 可以用标头修复,但是从客户端到标头,你无能为力来解决问题。您需要在服务器的响应中包含 CORS 标头。
-
CORS 可能很难理解。我发现以下内容很有帮助:developer.mozilla.org/en-US/docs/Web/HTTP/CORS