如何解决CORS 在不同端口上使用 React 前端的 Rails 6 不工作
在 http://localhost:3000
上运行 rails 6.1.1 开发服务器(通过 rails s
)
在 http://localhost:3001
上响应客户端(通过 yarn start
)
我已经尝试了以下
在 gemfile 中,gem 'rack-cors'
和 bundle install
在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,:options]
end
end
来自 react js 客户端的示例 axios 请求
axios.post('http://localhost:3000/users',{user},{withCredentials: true})
.then(response => {
...
})
.catch(error => console.log('api errors:',error))
};
还尝试将 localhost
替换为 127.0.0.1
,在配置中添加 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.
解决方法
如果您已经设置了 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 };
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。