跨域请求被Sinatra和ReactJS阻止

问题描述 投票:0回答:1

我正在用ReactJS前端构建一个简单的Sinatra后端。当我尝试从React应用程序向我的Sinatra项目中的路线发出请求时,它给我CORS错误。我试图像这样在我的项目中启用CORS,但是没有用:

require 'sinatra'
require 'sinatra/cross_origin'
require 'json'

configure do
    enable :cross_origin
end

set :allow_origin, :any
set :allow_methods, [:get, :post, :options]
set :allow_credentials, true
set :max_age, "1728000"
set :expose_headers, ['Content-Type']

get '/' do 
    'Hello!'    
end

post '/download' do
    content_type :json

    return {res: params['songs']}.to_json
end

所以当我从React发出这样的请求时:

axios.post('http://localhost:4567/download', {}, {
    songs: this.state.songs
}).then(res => {
    console.log(res.data)
})

我收到一个CORS错误,看起来像这样:enter image description here

并且我在控制台中收到此错误:enter image description here

我应该在我的Sinatra / React项目中进行哪些更改以使其正常工作,以便可以从React向Sinatra发出请求?

ruby cors sinatra
1个回答
0
投票

请参见https://github.com/britg/sinatra-cross_origin#responding-to-options。显然,您需要添加自己的代码来手动处理OPTIONS请求-因为sinatra-cross_origin gem本身实际上并不处理OPTIONS请求。具体来说,您显然需要添加以下内容:

options "*" do
  response.headers["Access-Control-Allow-Methods"] = "HEAD,GET,PUT,POST,DELETE,OPTIONS"
  response.headers["Access-Control-Allow-Headers"] = "Content-Type"
  200
end
© www.soinside.com 2019 - 2024. All rights reserved.