Newtt
Newtt

Reputation: 6190

POST JSON response to HTTP request in Ruby

I'm running a Ruby app on Heroku. The app returns a JSON which is accessible when I go to the debugger of my browser. The JSON response is of the following template:

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

Sample response:

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

the code i wrote to achieve this is:

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

When I try to access this link using

$.getJSON('app-url',function(data){
    console.log(data);
});

it gives me an error saying

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

Is there a way for me to directly access the JSON response by writing the JSON to the HTTP response?

Upvotes: 0

Views: 452

Answers (1)

TheDude
TheDude

Reputation: 3952

So I am guessing that the page you are making the get request from is not served up by Sinatra. You can add the header Access-Control-Allow-Origin: * to that request to make it work.

This answer shows how to do it by either using response['Access-Control-Allow-Origin'] = * or headers( "Access-Control-Allow-Origin" => "*" )

That answer also lists this blog post as a reference to Cross Origin Resource Sharing in Sinatra.

Upvotes: 1

Related Questions