本文介绍了如何添加“Access-Control-Allow-Origin"Ruby 中 API 响应的标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在面试前端开发人员的工作,并接受了编码测试以构建一个简单的前端界面.我得到了服务器,它是用 Ruby (2.1.3) 编写的,有 3 个端点,我将在我的前端客户端中使用它们.我对 Ruby 没有任何经验,但我按照他们的说明设置服务器,它似乎工作 - 我从所有端点得到响应.问题是我的客户端应用程序没有得到任何响应,它位于不同的域"中(实际上,它们都只是本地主机的不同端口).似乎他们没有在 API 上设置Access-Control-Allow-Origin"标头,但我不想回到他们那里询问如何解决这个问题,因为我担心它会在我的测试中反映出来.

I'm interviewing for a front-end developer job and have been given a coding test to build a simple front-end interface. I've been given the server, which has been written in Ruby (2.1.3) and has 3 endpoints which I am to make use of in my front-end client. I have no experience whatsoever with Ruby but I followed their instructions for setting up the server and it seems to work - I get responses from all the endpoints. The problem is that I'm not getting any response from my client app, which is in a different "domain" (actually, they're both just different ports of localhost). It seems that they are not setting the "Access-Control-Allow-Origin" headers on the API, but I don't want to go back to them asking how to fix this because I'm afraid it will reflect poorly on my test.

下面是服务器文件结构,我还包含了一些似乎相关的文件的内容.如果有人想查看其他文件,请发表评论.我相信这对于任何了解 Ruby 的人来说都很简单,但我没有最模糊的线索.

Below is the server file structure and I've also included the contents of a few files which seem to be relevant. If anyone wants to see other files, please just comment. I'm sure this is simple for anyone who knows Ruby but I haven't the foggiest clue.

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

推荐答案

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

Sinatra is a simple and lightweight web server. The general idea is that you write response routes like this:

get '/api' do
 "Hello world"
end

当您向 yoursite.com/api 发出 HTTP GET 请求时,您将收到Hello world"作为响应.

When you make a HTTP GET request to yoursite.com/api you will get a "Hello world" as response.

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

Now to add the header you want, this should do the trick:

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

这篇关于如何添加“Access-Control-Allow-Origin"Ruby 中 API 响应的标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-21 11:11