0
votes

Can someone please help me with the next topic? I have an API in rails with the options to perform a full CRUD. I have tested the API using POSTMAN and it works well. But now I try to consume it and use it from a mobile app created with Ionic and Angular and only the GET option works. I have installed and configured the gem rack-cors. And I'm also doing tests with this portion of code in my controller. The error I get is the following. Thank you very much for your help, I am a student excuse me if something I am doing wrong.

config/application.rb

     config.middleware.insert_before 0, "Rack::Cors" do
        allow do
            origins '*'
            resource '*',
            headers: :any, 
            methods: [:get, :post, :options, :delete, :put]
        end
    end

controller in ANGULAR/IONIC APP

     Define the event resource, adding an update method
     var Event = $resource('http://localhost:3000/api/v1/books/:id', {id:'@id'},
     { 
         update: 
         {
            method: 'PUT'
         }
    });

    // Use get method to get the specific object by ID
    // If object found, update. Else throw error
    Event.get({'id': 1}).$promise.then(function(res) {
       // Success (object was found)

       // Set event equal to the response
       var e = res;

       // Pass in the information that needs to be updated
       e.title = "2000";

       // Update the resource using the custom method we created
       Event.update(e)

    }, function(errResponse) {
       // Failure, throw error (object not found)
       alert('event not found');
   });

this is the error:

XMLHttpRequest cannot load http://localhost:3000/api/v1/books/1. 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:5000' is therefore not allowed access. The response had HTTP status code 404.

1

1 Answers

0
votes

If you are using Angular 6 & Ionic. CLI supports Proxy Config which will proxy the backend API that will help for development.

https://github.com/angular/angular-cli/blob/master/docs/documentation/stories/proxy.md