crodev
crodev

Reputation: 1491

Cross-Origin Request Blocked with Sinatra and ReactJS

I am building a simple Sinatra backend with ReactJS frontend. When I try to make request to a route in my Sinatra project from React app it gives me CORS error. I tried to enable CORS in my project like this but it didn't work:

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

So when I do a request like this from React:

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

I get a CORS error which looks like this:
enter image description here

And I get this error in the console: enter image description here

What should I change in my Sinatra/React project to make this work so I can make requests from React to Sinatra?

Upvotes: 4

Views: 1110

Answers (2)

sideshowbarker
sideshowbarker

Reputation: 88186

See https://github.com/britg/sinatra-cross_origin#responding-to-options. You need to add your own code to manually handle OPTIONS requests — because the sinatra-cross_origin gem itself doesn’t actually handle OPTIONS requests. Specifically, you’d need to add this:

options "*" do
  response.headers["Access-Control-Allow-Methods"] = "HEAD,GET,PUT,POST,DELETE,OPTIONS"
  response.headers["Access-Control-Allow-Headers"] = "Content-Type"
  200
end

Upvotes: 2

Ray
Ray

Reputation: 241

I had the exact issue as you with Sinatra & React, after countless hours of searching I couldn't find any solution until I found this gem, https://github.com/jdesrosiers/sinatra-cors

Here's my solution which implements the basics:

require "sinatra/cors"

set :allow_origin, "*"
set :allow_methods, "GET,DELETE,PATCH,OPTIONS"
set :allow_headers, "X-Requested-With, X-HTTP-Method-Override, Content-Type, Cache-Control, Accept, if-modified-since"
set :expose_headers, "location,link"

Upvotes: 1

Related Questions