kodeslacker
kodeslacker

Reputation: 127

AngularJS and sinatra CORS

I am trying to do a post using AngularJS

$http.post('http://localhost:9393/doRegister',$scope.newUser).success (data)=>
  alert data

To a sinatra controller

    post '/doRegister' do
      data = request.body.read
      return data.password
    end

i used the following configuration for CORS

#CORS enable
before do
  headers['Access-Control-Allow-Methods'] = 'GET, POST, PUT, DELETE, OPTIONS'
  headers['Access-Control-Allow-Origin'] = '*'
  headers['Access-Control-Allow-Headers'] = 'accept, authorization, origin'
end

options '*' do
  response.headers['Allow'] = 'HEAD,GET,PUT,DELETE,OPTIONS,POST'
  # Needed for AngularJS
  response.headers['Access-Control-Allow-Headers'] = 'X-Requested-With, X-HTTP-Method-Override, Content-Type, Cache-Control, Accept'
end

but i still get the following error from chrome

XMLHttpRequest cannot load http://localhost:9393/doRegister. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4567' is therefore not allowed access. 

when i try to debug the app the console shows:

W, [2013-11-20T01:39:01.778466 #3716]  WARN -- : attack prevented by Rack::Protection::HttpOrigin
127.0.0.1 - - [20/Nov/2013 01:39:01] "POST /doRegister HTTP/1.1" 403 - 0.0016

i tried using the following, cors_enable gem, rack/cors gem i tried disabling rack protection using some options like the folowing

use Rack::Protection::HttpOrigin, :origin_whitelist => ['*']

set :protection, :origin_whitelist => ['http://localhost:5445']
set :protection, :except => :frame_options
set :protection, :except => :json_csrf
set :protection, :except => :http_origin

I am out of ideas, please advise.

Upvotes: 2

Views: 1550

Answers (2)

Marcelo Fonseca
Marcelo Fonseca

Reputation: 1844

I had some troubles trying to configure sinatra-cross_origin and i manage to make it work using rack-cors gem. Install it and add this to your config.ru

require 'rack/cors'

use Rack::Cors do
  allow do
    origins '*' # 'localhost:3000', 'localhost:8080', '0.0.0.0:3000', '127.0.0.1:3000',
    resource '*',  headers: :any, methods: [:get, :post, :delete, :put, :patch, :options, :head]
  end
end

Upvotes: 1

Neel Kamal
Neel Kamal

Reputation: 710

sinatra-cross_origin will help.

To install it run this command : gem install sinatra-cross_origin.

To enable cross origin requests for all routes:

require 'sinatra'
require 'sinatra/cross_origin'

configure do
  enable :cross_origin
end

Then Add these lines within routes

  cross_origin :allow_origin => '*',
    :allow_methods => [:get],
    :allow_credentials => false,
    :max_age => "60"

Example:

get '/custom' do
  cross_origin :allow_origin => 'http://example.com',
    :allow_methods => [:get],
    :allow_credentials => false,
    :max_age => "60"

  "My custom cross origin response"
end

For More details you can follow this link :sinatra-cross_origin

Upvotes: 3

Related Questions