【发布时间】:2013-09-25 15:50:06
【问题描述】:
我刚开始使用 angularjs,我使用 rails 作为后端 api。我已经成功地设置了角导轨资源(https://github.com/FineLinePrototyping/angularjs-rails-resource)和机架 cors 以从导轨获取数据。但是,当我尝试保存节日时,出现以下错误:
XMLHttpRequest cannot load http://localhost:3000/festivals. Origin http://localhost:9000 is not allowed by Access-Control-Allow-Origin.
这是我的代码,
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]
)
}
这是使用角轨资源的节日工厂
app/scripts/services/Festival.coffee
'use strict'
angular.module('MFNApp')
.factory 'Festival', (railsResourceFactory) ->
railsResourceFactory
url: 'http://localhost:3000/festivals',
name: 'festival'
这里是视图
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>
【问题讨论】:
-
使用 JavaScript 请求页面时,您必须确保端口匹配,如果您的 Web 服务器在端口 9000 上运行,它将只接受来自端口 9000 的页面。域和协议也是如此跨度>
-
是的,它们需要匹配,但我使用 rails 作为 api。这意味着我需要单独运行 rails 服务器,并且需要让它们彼此很好地交谈。我对这个主题有一个粗略的了解,所以我肯定是错的。
标签: javascript ruby-on-rails rest angularjs