Handling CORS for subdomain ajax requests in rack

966 views Asked by At

After looking at other questions and answers I find they don't really cover want I want to do, hence why I'm asking a new question.

So, I built a subdomain matching middleware for rack with the idea that I would host my api in it's own subdomain (api.localhost:3000).

This for the most part works however if I try to send an ajax request the web browser throws a hissy fit about CORS.

So how do I add in CORS for subdomains for my Subdomain matching middleware bearing in mind I'm working in rack for this.

1

There are 1 answers

5
yardpenalty.com On BEST ANSWER

If you can prevent the use of CORS or jsonp I suggest you do. The best solution would be to define a subdirectory to handle your API/restful requests. I had a similar situation and when you force yourself into CORS aka Header Always Set Access-Control-Allow-Origin * then you set yourself up for limitations.

Avoid these limitations when possible. Just my experience. Good luck!

I would do something like:

http://www.domain.com/rest/api/items/1

Where rest is where your web services are handled. Get away from subdomains if you don't need them.

If you must absolutely use CORS and you know that requests are handled by you and only you then you can get away with using jsonp.

jsonp

jsonp essentially wraps your request in a javascript object using the callback function. There are limitations to the amount of data you can handle using this approach, but it is a quick way to get your cross domain requests to work without setting up CORS.

Here is an example of a jsonp request:

  $.ajax({
           type: "GET",
           url:  "http://www.domain.com/rest/WEB055S?callback=?",
           data: args,
           contentType: "application/json; charset=utf-8",
           dataType: "jsonp"}).
           done(function(data){
               alert(data.ERROR);
           })...