Friday, June 22, 2012
Rails - Allow AJAX Request from Other Domain
As you have already known that by default, AJAX Request from other domain isn't allowed. Yes, cross domain AJAX request isn't allowed by default. Fortunately, there's a simple way to allow it (if you truly need to allow some particular domains to make AJAX request to your domain). But before you implement this way, please consider its security risk. So, do it on your own risk.
To allow AJAX Request from other domains to your domain, you need to write something like before_filter callback method. You can place it on your application controller. Here's the code for that method.
def allow_ajax_request_from_other_domains headers['Access-Control-Allow-Origin'] = 'example.com' headers['Access-Control-Request-Method'] = 'example.com' end
And call that method above in before_filter like this one
That's it. Now, example.com will be allowed to make AJAX Request to your web application. Be careful with this one, and make sure the domains you give that privileges is trusted domain. And don't try to make that method like the following one (because it will allow all domains in this world to make AJAX Request to yours)
def allow_ajax_request_from_other_domains headers['Access-Control-Allow-Origin'] = '*' headers['Access-Control-Request-Method'] = '*' end