我正在尝试使用ionic
和后端的示例项目Rails
.当我使用离子服务启动离子服务器并提交我的样本表格时
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 = {}; }) } }]){ "name": "kranthi_web", "app_id": "", "proxies": [ { "path": "/api", "proxyUrl": "http:localhost:3000/" } ] }
有人能告诉我,我在哪里做错了
CORS(跨源资源共享)策略旨在防止对不同域资产的XML请求.
基本上,如果您通过XML从不同的域/服务器请求资源,则需要确保在该服务器上具有相应的CORS策略来处理它.
默认情况下,Rails会阻止响应任何外部XML请求.解决这个问题的唯一方法是通过自己的CORS策略来允许资源.
该rack-cors
宝石是最好的这样:
#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请求.