【问题标题】:POST JSON response to HTTP request in RubyPOST JSON 响应 Ruby 中的 HTTP 请求
【发布时间】:2014-01-21 03:05:07
【问题描述】:

我正在 Heroku 上运行一个 Ruby 应用程序。该应用程序返回一个 JSON,当我转到浏览器的调试器时可以访问该 JSON。 JSON 响应的模板如下:

rates = {
    "Aluminium" => price[1],
    "Copper" => price_cu[1],
    "Lead" => price_pb[1],
    "Nickel" => price_ni[1],
    "Tin" => price_sn[1],
    "Zinc" => price_zn[1],
}

示例响应:

{
    "Aluminium":"1765.50",
    "Copper":"7379.00",
    "Lead":"2175.00",
    "Nickel":"14590.00",
    "Tin":"22375.00",
    "Zinc":"2067.00"
}

我为此编写的代码是:

Test.rb

class FooRunner
    def self.run!
        #calculations_for_rates
        rates.to_json
    end
if __FILE__ == $0
    puts FooRunner.run!
end

app.rb

require 'sinatra'
require './test.rb'

result = FooRunner.run!
File.open('output.json','w') do |f|
        f.write result
end

content_type :json
result

当我尝试使用

访问此链接时
$.getJSON('app-url',function(data){
    console.log(data);
});

它给了我一个错误提示

No 'Access-Control-Allow-Origin' header is present on the requested resource.

有没有办法让我通过将 JSON 写入 HTTP 响应来直接访问 JSON 响应?

【问题讨论】:

标签: ruby json heroku


【解决方案1】:

所以我猜你发出get 请求的页面不是由Sinatra 提供的。您可以将标头 Access-Control-Allow-Origin: * 添加到该请求中以使其正常工作。

This answer 展示了如何使用response['Access-Control-Allow-Origin'] = *headers( "Access-Control-Allow-Origin" => "*" ) 来完成此操作

该答案还列出了 this blog post 作为对 Sinatra 中跨域资源共享的引用。

【讨论】: