CORS 无法在不同端口上使用 React 前端的 Rails 6 上运行
Posted
技术标签:
【中文标题】CORS 无法在不同端口上使用 React 前端的 Rails 6 上运行【英文标题】:CORS not working on Rails 6 with React frontend on different ports 【发布时间】: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.
【问题讨论】:
【参考方案1】:如果您已经设置了config/initializers/cors.rb
,则无需在application.rb
中添加配置
遇到了同样的问题,我对cors.rb
的设置如下:
Rails.application.config do |config|
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', headers: :any, methods: [:get, :post, :patch, :put]
end
end
end
但是,这就是我创建 axios 请求的方式(请注意标头部分):
let service = axios.create(
headers:
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*' <=== notice this header here
,
baseURL: process.env.VUE_APP_API_PATH
);
service.interceptors.response.use(this.handleSuccess, this.handleError);
this.service = service;
并像这样使用它:
this.service.request(
method: 'POST',
url: path,
responseType: 'json',
data: payload
).then((response) =>
return status: response.status, data: response.data ;
);
【讨论】:
以上是关于CORS 无法在不同端口上使用 React 前端的 Rails 6 上运行的主要内容,如果未能解决你的问题,请参考以下文章
React/Redux 前端和 Node.js 后端之间的 CORS 问题 [重复]
将 Apollo 反应到不同端口上的 graphql-php 服务器
Webpack devserver 代理无法解决 CORS 问题
将Apollo反应到不同端口上的graphql-php服务器