【问题标题】:CORS issue in ionic with rails带有导轨的离子中的CORS问题
【发布时间】:2016-03-23 19:52:24
【问题描述】:

我正在尝试使用ionic 和后端为Rails 的示例项目。当我使用 ionic serve 启动离子服务器并提交我的示例表单时,

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

尝试了一些我在谷歌得到的答案,但无法通过它。 下面是我的 app.js 代码 index.html 和 ionic.project 文件代码。

angular.module('starter', ['ionic'])

.run(function($ionicPlatform) {
  $ionicPlatform.ready(function() {
    if(window.cordova && window.cordova.plugins.Keyboard) {
      cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
      cordova.plugins.Keyboard.disableScroll(true);
    }
    if(window.StatusBar) {
      StatusBar.styleDefault();
    }
  });
})

.constant('ApiEndpoint',  'http://localhost:3000/')

.config(function($stateProvider, $urlRouterProvider) {
  $stateProvider
  .state('signUp',{
    cache: false,
    url: "/signUp",
    templateUrl: "templates/signUp.html",
    controller: 'ExampleCtrl'
  }) 

  $urlRouterProvider.otherwise("/signUp");
})

.controller('ExampleCtrl', ['$scope','$http','ApiEndpoint', function ($scope, $http, ApiEndpoint) {

  $scope.registrationForm = {};

  $scope.signUp = function(){
    console.log($scope.registrationForm);
    console.log(ApiEndpoint);
     $http.post(ApiEndpoint + "signup", {a: 1}).then(function(result){
       console.log(result);
       $scope.registrationForm = {};
     }, function(error){
       console.log(error);
       $scope.registrationForm = {};
     })
  }
}])


<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
    <meta http-equiv="Content-Security-Policy" content="default-src *; style-src 'self' 'unsafe-inline'; script-src 'self' 'unsafe-inline' 'unsafe-eval'">
    <title></title>

    <link href="lib/ionic/css/ionic.css" rel="stylesheet">
    <link href="css/style.css" rel="stylesheet">

    <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
    <link href="css/ionic.app.css" rel="stylesheet">
    -->

    <!-- ionic/angularjs js -->
    <script src="lib/ionic/js/ionic.bundle.js"></script>

    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>

    <!-- your app's js -->
    <script src="js/app.js"></script>
  </head>
  <body ng-app="starter" animation="slide-left-right-ios7">
    <ion-pane>
      <ion-nav-bar class="nav-title-slide-ios7 bar-stable">
        <ion-nav-back-button></ion-nav-back-button>
      </ion-nav-bar>
      <ion-nav-view>
      </ion-nav-view>
    </ion-pane>
  </body>

</html>

{
  "name": "kranthi_web",
  "app_id": "",
  "proxies": [
    {
      "path": "/api",
      "proxyUrl": "http:localhost:3000/"
    }
  ]
}

谁能告诉我哪里做错了

【问题讨论】:

    标签: ruby-on-rails angularjs ionic cors


    【解决方案1】:

    CORS (Cross Origin Resource Sharing) 策略旨在防止对不同域资产的 XML 请求。

    基本上,如果您通过 XML 从不同的域/服务器请求资源,则需要确保在该服务器上有相应的 CORS 策略来处理它。


    默认情况下,Rails 会阻止响应任何外部 XML 请求。解决此问题的唯一方法是通过您自己的 CORS 策略允许该资源。

    rack-cors gem 最适合这个:

    #config/application.rb
    # ...
    
    config.middleware.insert_before 0, "Rack::Cors" do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end
    

    如果您为您的域(IE localhost 或其他)设置了上述内容,您应该能够从您的前端 JS 访问您的后端。

    ...请记住,使用 Angular / 其他 JS 类型的框架,您每次都会发送 XML 请求。

    【讨论】:

    • 但我想发送 Json 请求而不是 XML。所以我可以知道应该为这种情况做些什么
    • 我认为 JSON 请求仍将通过 XHR 请求类型。您应该尝试我提供的代码,看看它是否有效。如果它有效,那么你可以弄清楚如何让它成为 JSON
    • 当然。非常感谢! :-)
    • 啊!!!..工作..非常感谢!..尝试了很多答案并花了很多时间。非常感谢!!!
    • 我正在尝试将我的 Ionic 移动应用程序重新用于 web 以及 rails 并且遇到了这个问题..感谢您的解决方案!
    【解决方案2】:

    在您的基本控制器中,您应该提供 Access-Control-Allow-Origin 标头。

       class Api::BaseController < ActionController::Base
    
          before_action :cors_preflight_check
          after_action :cors_set_access_control_headers
    
          protected
    
          def cors_preflight_check
            if request.method == 'OPTIONS'
              headers['Access-Control-Allow-Origin'] = '*'
              # ...
            end
          end
    
          def cors_set_access_control_headers
            headers['Access-Control-Allow-Origin'] = '*'
            # ...
          end
        end
    

    【讨论】:

      猜你喜欢
      • 2019-03-04
      • 2019-05-29
      • 2019-02-22
      • 1970-01-01
      • 2021-01-02
      • 2016-09-17
      • 2017-04-27
      • 2017-09-14
      • 1970-01-01
      相关资源
      最近更新 更多