2014-01-20 54 views
0

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

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 

应用.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 JSON响应到HTTP响应?

+0

[Sinatra access-control-allow-origin for sinatra公用文件夹]的可能重复(http://stackoverflow.com/questions/7109971/sinatra-access-control-allow-origin-for-sinatra-public-folder ) – TheDude

回答

1

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

This answer说明介绍如何使用response['Access-Control-Allow-Origin'] = *headers("Access-Control-Allow-Origin" => "*")

这个问题的答案还列出this blog post在西纳特拉参考,跨源资源共享去做。