繁体   English   中英

React Redux <No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access>

[英]React Redux <No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access>

我正在app中使用React + Redux + RoR。 我必须做社交登录。 对于客户端我使用davezuko / react-redux-starter-kit,它位于localhost:3000。 我的服务器 - localhost:5000。 从客户端到服务器的所有请求都没有问题(PUT,GET,POST)。 当我尝试使用twitter登录时(它在服务器上工作,localhost:5000 / auth / twitter - 使用来自twitter的params在DB中创建新用户)我有一个错误:

Failed to load https://api.twitter.com/oauth/authenticate?oauth_token=xxxxx: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access.

在客户端我称之为:

export const requestTest = async () => {
return axios.get('http://localhost:5000/auth/twitter', {}).then(function (response) {
        console.log('cors')
    console.log(response)
    return response.data
})

};

我该如何解决?

如果您的React dev服务器源不同于Rails应用程序服务器源(即使只是端口号),Rails认为该请求是跨源的。

当Rails收到此类请求时,除非设置了CORS策略,否则它会拒绝它。

最简单的方法是(可能)使用rack-cors gem:

1)添加

gem 'rack-cors', require: 'rack/cors'

到你的Gemfile

2) bundle install

3)添加

# see gem page for more examples
config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins /\Ahttp:\/\/localhost:\d+\z/
    resource '*', headers: :any, methods: :any
  end
end

在您的config/application.rb中的class Application < Rails::Application

4)重启rails。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM