【问题标题】:Rails server & React client: CORS issues despite same originRails 服务器和 React 客户端:尽管来源相同,但 CORS 问题
【发布时间】:2021-01-26 00:30:20
【问题描述】:
  • 我有一个带有 rack-cors 的 Rails API 服务器,它允许从 localhostserver 访问(Docker 容器名称,可以从 Node.js 服务器访问,可以正常使用)。
  • 当我在localhost 中直接从我的浏览器向我的服务器运行任何请求时,它运行良好。
  • 当我在 React 中使用 axios.get() 发出请求时(从我的客户端 localhost:3000 运行到我的服务器 localhost:3001),尽管请求在Rails 服务器端:
Access to XMLHttpRequest at 'http://localhost:3001/items' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

知道哪里出了问题吗?

# config/initializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'localhost', 'server' 
    resource '*', headers: :any, methods: %i[get post patch put delete options]
  end
end

【问题讨论】:

  • ports 对 cors 很重要,所以你需要在本地添加 localhost:3001 或者你可以在本地添加 proxy requests 并且在部署之前不用担心 cors
  • 好点,但为什么我没有找到很多关于在 CORS 策略中指定端口的文档? localhost:3001 不起作用,localhost:* 也不起作用,目前只有 * 起作用:-/
  • 没关系,它是localhost:3000,因为它是请求者(我的客户端应用程序)的主机。

标签: ruby-on-rails reactjs axios cors


【解决方案1】:

感谢@DCTID 的帮助,我发现必须在 Rails CORS 配置文件中指定端口。由于我想允许来自这些域的任何端口,所以我输入了这个正则表达式(需要 http:// 前缀):

origins %r{\Ahttp://(localhost|server)(:\d+)?\z}

【讨论】:

    猜你喜欢
    • 2015-06-25
    • 1970-01-01
    • 1970-01-01
    • 2011-05-26
    • 1970-01-01
    • 2012-12-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多