【发布时间】:2021-04-22 05:10:23
【问题描述】:
在http://localhost:3000(通过rails s)上运行rails 6.1.1 开发服务器
在http://localhost:3001 上响应客户端(通过yarn start)
我已经尝试了以下
在 gemfile 中,gem 'rack-cors' 和捆绑安装
在config/intializers/cors.rb
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
在application.rb
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
来自 react js 客户端的示例 axios 请求
axios.post('http://localhost:3000/users', {user}, {withCredentials: true})
.then(response => {
...
})
.catch(error => console.log('api errors:', error))
};
还尝试用127.0.0.1 替换localhost,在配置中添加http://,但没有一个解决方案有效
响应错误说被 CORS 政策阻止
Access to XMLHttpRequest at 'http://localhost:3000/users' from origin 'http://localhost:3001' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
【问题讨论】:
标签: ruby-on-rails reactjs axios cors ruby-on-rails-6