我刚开始使用 angularjs,我使用 rails 作为后端 api。我已经成功设置了 angular rails resouce ( https://github.com/FineLinePrototyping/angularjs-rails-resource ) 和 rack cors 以从 rails 获取数据。但是,当我尝试保存节日时,出现以下错误:
XMLHttpRequest cannot load http://localhost:3000/festivals. Origin http://localhost:9000 is not allowed by Access-Control-Allow-Origin.
这是我的代码,
应用程序/脚本/指令/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]
)
}
这是使用角轨资源的节日工厂
应用程序/脚本/服务/Festival.coffee
'use strict'
angular.module('MFNApp')
.factory 'Festival', (railsResourceFactory) ->
railsResourceFactory
url: 'http://localhost:3000/festivals',
name: 'festival'
这是视图
应用程序/视图/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>