Question

I've been struggle a little bit.

I have my Sinatra Web Server using Rack as a middleware as I need to have several Sinatra's applications.

The application is going to be a REST API that returns a json reponse, so in my Sinatra Application I have something like :

get "/:product/items" do
  content_type :json
  ## This will get you a JSON response 
  get_items("product")
end

If you go to http: //myapp/product/items/ in the browser I will get the json response

but now when I am trying to consume this api from JQuery

jQuery.getJSON("//myapp/product/items", populate);

I am getting a empty response in my console log

These are the headers :

Age 0
Cache-Control   public, max-age=1800
Connection  Keep-Alive
Content-Length  1443
Content-Type    application/json;charset=utf-8
Date    Wed, 19 Feb 2014 19:11:12 GMT
Server  WEBrick/1.3.1 (Ruby/2.0.0/2013-11-22)
X-Content-Digest    d55b64d8ec2c3e349fa799d3f15ae0f482850182
X-Content-Type-Options  nosniff
X-Rack-Cache    miss, store

Request Headers
Accept  application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language en-US,en;q=0.5
Host    localhost:9292
Origin  http://localhost
Referer http://localhost/index.htmk
User-Agent  Mozilla/5.0 (X11; Linux x86_64; rv:26.0) Gecko/20100101 Firefox/26.0

If you check the headers you will see a good response with the content-Type: json and the length of the content, but the in the response body there is nothing.

If I use

Jquery.getJSON("//myapp/product_name/items?callback=?", populate)

Works... even so I don't want to do that because I want to caching the response for an hour, if I use the callback=? I am getting a Jquery response but I don't want that as it is going to generate a Random number that refers to the function that I am going to use.

So I'm not sure if there is something about the response or Am I missing something ?

Thank you

Was it helpful?

Solution

I found the problem looks like I am missing the Access-Control-Allow-Origin header that actually makes sense and I forgot about it.

I didn't know that if you don't have means that you are not able to do a X-domain request so, I just use this gem sinatra/cross-origin and it would be the trick

Code:

require 'sinatra/cross_origin'

set :allow_origin, :any

configure do
  enable :cross_origin
end

OTHER TIPS

It looks like your request has a typo in your question ("propducts") - Check that's not the case in your app.

Also take a look at your Sinatra logs to see if the route was hit and if any items are found when you make the request

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top