【问题标题】:Cannot fetch data from Rails at ReactJS无法在 ReactJS 从 Rails 获取数据
【发布时间】: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


【解决方案1】:

阅读更多关于CORS

要解决此问题,您需要在 Gemfile 中添加 rack-cors gem gem 'rack-cors'

config/application.rb

# Rails 5

config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins '*'
    resource '*', headers: :any, methods: [:get, :post, :options]
  end
end

# Rails 3/4

config.middleware.insert_before 0, "Rack::Cors" do
  allow do
    origins '*'
    resource '*', headers: :any, methods: [:get, :post, :options]
  end
end

这对您当地的人来说就足够了。如果您部署代码,则需要对其进行修改。

【讨论】:

    【解决方案2】:

    正如评论所说,这是一个 CORS 错误。

    你可以根据这个问题allow-anything-through-cors-policy修复它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-10-12
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-30
      • 2020-03-23
      • 1970-01-01
      相关资源
      最近更新 更多