McFlyyy pointed out another solution to solve this problem. I haven’t tested it myself so follow it at your own risk Click Here
I was trying to use Rails to build REST API for my AngularJS app and came across CORS error on my Chrome developer tools.
According to Alexey Vasiliev, Cross-origin resource sharing (CORS) is a web browser technology specification which defines ways for a web server to allow its resources to be accessed by a web page from a different domain. Such access would otherwise be forbidden by the same origin policy. CORS defines a way in which the browser and the server can interact to determine whether or not to allow the cross-origin request. It is a compromise that allows greater flexibility, but is more secure than simply allowing all such requests. CORS is supported in the following browsers:
After following couple of outdated tutorials, I found the quick solution for it. Here are the steps:
Add route to handle OPTIONS method
AngularJS using OPTIONS method to check the CORS support on the API server. Thus, you need to add line in your route file to handle this. This can be done by adding code like this
|
|
To check whether your configuration is correct you can run ‘rake routes’. It should print out something like this:
|
|
You can see on the second line, we handle OPTIONS verb and redirect to index action.
Add before_filter and after_filter to allow CORS
The next step is we need to return proper header to tell AngularJS that our server allow CORS. Here is the sample controller file:
|
|
We need to add skip_before_filter :verify_authenticity_token because Rails will return 422 status code and error message ‘Can’t verify CSRF token authenticity’