每当我尝试使用React中的'fetch'方法从我的REST API中获取数据时,我得到'已被CORS策略阻止:没有'Access-Control-Allow-Origin'错误。我从研究中做到了,发现它可以通过标题来解决?事情是我是新的反应和使用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>
);
}
}
}
这不是反应问题。你必须在后端解决它。