从Angular / IOnic App到Rails API的CRUD

时间:2018-08-21 04:14:50

标签: ruby-on-rails angular api ionic-framework

有人可以帮我解决下一个话题吗? 我在Rails中有一个API,可以选择执行完整的 CRUD 。我已经使用 POSTMAN 测试了API,并且效果很好。但是现在我尝试使用它,并通过Ionic和Angular创建的移动应用程序使用它,并且只有GET选项起作用。 我已经安装并配置了gem rack-cors。 而且我还在控制器中使用这部分代码进行测试。 我得到的错误如下。 非常感谢您的帮助,如果我做错了事,我是一名学生,请原谅。

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
ANGULAR / IONIC APP 中的

controller

     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');
   });

这是错误:

  

XMLHttpRequest无法加载http://localhost:3000/api/v1/books/1。   对预检请求的响应未通过访问控制检查:否   请求中存在“ Access-Control-Allow-Origin”标头   资源。因此,不允许原点“ http://localhost:5000”   访问。响应的HTTP状态代码为404。

1 个答案:

答案 0 :(得分:0)

如果您使用的是Angular 6和Ionic。 CLI支持代理配置,代理配置将代理有助于开发的后端API。

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