【发布时间】:2020-02-27 10:12:09
【问题描述】:
我使用的前端源是端口 5555 的 ReactJS,我的后端是端口 8888 的 Rails。我试图通过使用以下方法从 Rails 获取数据:
const url = 'http://localhost:8888/problems';
fetch(url)
.then(res => {
res.json();
})
.then(response => {
console.log(response);
})
.catch(error => {
console.log(error);
});
但我收到了消息:
Access to fetch at 'http://localhost:8888/problems' from origin 'http://localhost:5555' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
我不知道那个错误。请帮我解决它
【问题讨论】:
-
您从浏览器收到 CORS 错误。您的 Rails 服务器需要设置标题
Access-Control-Allow-Origin: *。这是因为由于端口不同,您的网页和服务器在技术上是不同的来源。 -
跟reactjs没关系。是CORS问题,在rails中查看如何处理:stackoverflow.com/questions/29751115/…
-
@Benjamin 我应该在哪里设置?
标签: ruby-on-rails reactjs fetch-api