Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allow cross domain access on Rails server

I have a front end web app in Angular and back end in Rails. From front-end I have javascript code issuing POST http request:

$scope.onSave = function () {
        $http.post('http://localhost:3000/documents', { user: $scope.user, formData: $scope.formData }, function (response) {
            $scope.isSaved = true;
            console.log(response);
            if (response.success) {
                console.log("It has been successfully saved!")
            }
        });
}

And on submit button, I call above function:

<button type="submit" class="btn btn-success" ng-click="onSave()">Submit</button>

Then I get an error saying

XMLHttpRequest cannot load http://localhost:3000/documents. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3001' is therefore not allowed access. The response had HTTP status code 404.

I know i need to allow cross domain access but I'm not sure how I can achieve this in Rails server side.

like image 377
Kahsn Avatar asked Feb 07 '23 06:02

Kahsn


2 Answers

  1. Add this gem "rack-cors" to your Gemfile.

  2. Add this to your config/application.rb file.

   config.middleware.insert_before 0, Rack::Cors do
        allow do
            origins '*'
            resource '*',
              headers: :any,
              methods: [:get, :post, :patch, :delete, :put, :options]
        end
    end
like image 189
Christopher Harris Avatar answered Feb 10 '23 08:02

Christopher Harris


I had a need to query multiple APIs running on the same server with different port addresses. I have been playing around with using an "Ajax" controller that just passes through the requests via HTTParty and renders the response in JSON:

class AjaxController < ApplicationController

   def query
     port = params['port']
     path = params['path']
     url = "http://0.0.0.0:#{port}/#{path}"
     response = HTTParty.get(url)
     render json: response
   end

end

The query is scripted (for example):

 <script>
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {
            myObj = JSON.parse(this.responseText);
            document.getElementById("demo").innerHTML = myObj.plans;
        }
    };
    xmlhttp.open("GET", "/ajax/query?port=3005&path=items.json?state=TX",true);
    xmlhttp.send();
</script>

Obviously this approach needs to be secured, but perhaps it will yield some further ideas.

like image 36
guero64 Avatar answered Feb 10 '23 07:02

guero64