[英]Angularjs Rails- Origin http://localhost:9000 is not allowed by Access-Control-Allow-Origin.
I just started out with angularjs and I am using rails as a backend api. 我刚开始使用angularjs,并且使用rails作为后端api。 I have successfully setup angular rails resouce ( https://github.com/FineLinePrototyping/angularjs-rails-resource ) and rack cors to get data from rails. 我已经成功设置了角轨资源( https://github.com/FineLinePrototyping/angularjs-rails-resource )和机架cors以从轨中获取数据。 When I try to save a festival though, I get the following error: 但是,当我尝试保存节日时,出现以下错误:
XMLHttpRequest cannot load http://localhost:3000/festivals. Origin http://localhost:9000 is not allowed by Access-Control-Allow-Origin.
Here's my code, 这是我的代码,
app/scripts/directives/festival_form.coffee app / scripts / directives / festival_form.coffee
'use strict'
angular.module('MFNApp')
.directive 'festivalForm', ->
return {
compile: (scope, element, attributes) ->
console.log 'compile'
link: (scope, element, attributes) ->
console.log 'link'
controller: ($scope, Festival) ->
$scope.newFestival = new Festival
console.log $scope.newFestival
$scope.save = ->
$scope.newFestival.save().then(
(festival) ->
console.log 'success'
# $scope.festivalForm.$setPristine()
# $scope.newFestival.$dirty = false
,
(response) ->
console.log 'failure'
# $scope.festivalForm.$setValidity(false)
# angular.forEach response.data, (value, key) ->
# $scope.festivalForm.$error[key] = value[0]
)
}
Here's the festival factory using angular rails resource 这是使用斜轨资源的节日工厂
app/scripts/services/Festival.coffee 应用程序/脚本/服务/Festival.coffee
'use strict'
angular.module('MFNApp')
.factory 'Festival', (railsResourceFactory) ->
railsResourceFactory
url: 'http://localhost:3000/festivals',
name: 'festival'
And here is the view 这是视图
app/views/fesitvals/new.html app / views / fesitvals / new.html
<div festival-form>
<form>
<fieldset>
<legend>Festival Information</legend>
<div class="row">
<div class="large-12 columns">
<label>Festival Name</label>
<input ng-model='newFestival.name' type="text" placeholder="Name of your festival...">
</div>
</div>
<div class="row">
<div class="large-12 columns">
<label>Description</label>
<input ng-model='newFestival.description' type="text" placeholder="About your festival...">
</div>
</div>
<button ng-click='save()'>Save</button>
</fieldset>
</form>
</div>
您必须允许Web api接受来自该域( http://localhost:9000
)的请求,或者可以按此处所述为所有域打开它, 通过CORS Policy允许任何操作
The error was a little misleading, because it seemed to be a cross origin request error. 该错误有点误导,因为它似乎是跨源请求错误。 It was actually just an error in the rails controller. 实际上,这只是rails控制器中的错误。 So if you ever hook up rails as a backend to angular and encounter this error, it could just be incorrect rails code. 因此,如果您曾经将rails挂接到angular的后端并遇到此错误,则可能是不正确的rails代码。 hope this helps! 希望这可以帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.