如何添加" Access-Control-Allow-Origin" Ruby中的API响应标头

时间:2017-02-25 09:46:14

标签: ruby sinatra

我正在面试一个前端开发人员的工作,并且已经过编码测试以构建一个简单的前端界面。我已经获得了服务器,该服务器是用Ruby(2.1.3)编写的,并且有3个端点,我将在我的前端客户端中使用它。我没有使用Ruby的任何经验,但我按照他们的说明设置服务器,它似乎工作 - 我从所有端点得到响应。问题是我没有从我的客户端应用程序得到任何响应,这是一个不同的域名#34; (实际上,它们只是localhost的不同端口)。似乎他们没有设置" Access-Control-Allow-Origin"关于API的标题,但我不想回复他们询问如何解决这个问题,因为我担心它会在我的测试中反映不佳。

下面是服务器文件结构,我还包括一些似乎相关的文件的内容。如果有人想看到其他文件,请发表评论。对于那些了解Ruby的人来说,我确信这很简单,但我并不是最模糊的线索。

D:.
¦   .gitkeep
¦   client.rb
¦   config.ru
¦   foo.sqlite3
¦   Gemfile
¦   Gemfile.lock
¦   Rakefile
¦   README.md
¦
+---app
¦   +---controllers
¦   ¦       api_controller.rb
¦   ¦       application_controller.rb
¦   ¦       not_found_controller.rb
¦   ¦       payments_controller.rb
¦   ¦
¦   +---models
¦   ¦       payment.rb
¦   ¦
¦   +---views
¦           booking.html
¦           confirmation.html
¦
+---config
¦       boot.rb
¦       dispatcher.rb
¦
+---db
¦   ¦   schema.rb
¦   ¦   seeds.rb
¦   ¦
¦   +---migrate
¦           20150331094122_create_payments.rb
¦
+---lib
¦       my_application.rb
¦
+---log
¦       development.log
¦       test.log
¦
+---public
¦   ¦   404.html
¦   ¦   500.html
¦   ¦
¦   +---css
¦           style.css
¦
+---script
¦       console
¦       server
¦
+---spec
¦   ¦   spec_helper.rb
¦   ¦
¦   +---acceptance
¦   ¦       api_endpoint_spec.rb
¦   ¦       not_found_spec.rb
¦   ¦
¦   +---models
¦           payment_spec.rb
¦
+---vendor
    +---libs
            foobar_goodies

的boot.rb

ENV['RACK_ENV'] ||= 'development'

# Bundler
require 'bundler/setup'
Bundler.require :default, ENV['RACK_ENV'].to_sym

require_relative '../lib/my_application.rb'

root_path = MyApplication.root
lib_path = File.join(MyApplication.root, 'lib')
app_path = File.join(MyApplication.root, 'app')
[root_path, lib_path, app_path].each { |path| $LOAD_PATH.unshift(path) }

ENV['PEERTRANSFER_ROOT'] = root_path

require 'config/dispatcher'
require 'sinatra/activerecord'

set :database, { adapter: "sqlite3", database: "foo.sqlite3" }

require 'app/models/payment'

my_application.rb

module MyApplication
  class << self
    def root
      File.dirname(__FILE__) + '/..'
    end

    def views_path
      root + '/app/views'
    end

    def public_folder
      root + '/public'
    end
  end
end

dispatcher.rb

require 'controllers/application_controller'
require 'controllers/not_found_controller'

require 'controllers/api_controller'
require 'controllers/payments_controller'

module MyApplication
  class Dispatcher
    def call(env)
      path_info = env['PATH_INFO']

      app = case path_info
        when %r{^/api} then ApiController.new
        when %r{^/payment} then PaymentsController.new
        else NotFoundController.new
      end

      app.call(env)
    end
  end
end

application_controller.rb

class ApplicationController < Sinatra::Base
  set :views, MyApplication.views_path
  set :public_folder, MyApplication.public_folder

  not_found do
    html_path = File.join(settings.public_folder, '404.html')
    File.read(html_path)
  end

  error do
    raise request.env['sinatra.error'] if self.class.test?

    File.read(File.join(settings.public_folder, '500.html'))
  end
end

api_endpoint_spec.rb

require 'spec_helper'
require 'models/payment'

describe 'API Endpoint' do
  it 'responds with a JSON welcoming message' do
    get '/api'

    expect(last_response.status).to eq(200)
    expect(last_response.body).to eq('{"message":"Hello Developer"}')
  end

  it 'returns all the stored payments' do
    Payment.all.map(&:delete)
    Payment.new(reference: 'any reference', amount: 10000).save

    get '/api/bookings'

    expect(last_response.status).to eq(200)
    expect(last_response.body).to eq("{\"bookings\":[{\"reference\":\"any reference\",\"amount\":10000,\"country_from\":null,\"sender_full_name\":null,\"sender_address\":null,\"school\":null,\"currency_from\":null,\"student_id\":null,\"email\":null}]}")
  end

  def app
    MyApplication::Dispatcher.new
  end
end

1 个答案:

答案 0 :(得分:2)

Sinatra是一个简单轻量级的Web服务器。一般的想法是你写这样的响应路线:

get '/api' do
 "Hello world"
end

当您向yoursite.com/api发出HTTP GET请求时,您将获得一个&#34; Hello world&#34;作为回应。

现在要添加你想要的标题,这应该可以解决问题:

get '/api' do
  response['Access-Control-Allow-Origin'] = '*'
  "Hello world"
end