【发布时间】:2021-12-11 18:51:24
【问题描述】:
我创建了一个小型 API,用于抓取火车到达/出发的网页。我将它托管在 Heroku 上,当我访问页面时:https://sl-scraper.herokuapp.com/fromstockholm 我可以看到我期望的 JSON 响应。看起来像这样:
到目前为止一切都很好。现在我希望在我的 React 应用程序中获取这些数据,以便以更好的方式显示它。这是我遇到问题的地方。我尝试通过两种方式获取信息,但两种方式都会导致相同的问题。
这是第一次尝试:
React.useEffect(function(){
axios.get("https://sl-scraper.herokuapp.com/fromstockholm")
.then(response =>{
console.log(response);
})
.catch(err => console.log(err));
},[]);
这是第二次尝试:
React.useEffect(()=>{
fetch("https://sl-scraper.herokuapp.com/fromstockholm")
.then(response => {
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => console.log(error));
},[]);
当我检查日志时,这两种尝试都会导致此问题:
从源“http://localhost:3000”访问“https://sl-scraper.herokuapp.com/fromstockholm”上的 XMLHttpRequest 已被 CORS 策略阻止:没有“访问控制允许源”请求的资源上存在标头。
有人知道我为什么会收到这些错误吗?非常感谢您。
【问题讨论】:
-
我在您的屏幕截图中看到了错误,但仅供参考 HTTP 200 Ok 表示成功,而不是错误。我不确定您在哪里看到 200 响应,但这可能不是问题所在。
-
@Chris 好的,我将 React 应用程序上传到 Netlify 并尝试运行它。我得到同样的错误..你介意看看最新的答案吗?我在那里更新了它。
标签: reactjs heroku axios cors fetch