[英]Angularjs Rails- Origin http://localhost:9000 is not allowed by Access-Control-Allow-Origin.
我剛開始使用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]
)
}
這是使用斜軌資源的節日工廠
應用程序/腳本/服務/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>
您必須允許Web api接受來自該域( http://localhost:9000
)的請求,或者可以按此處所述為所有域打開它, 通過CORS Policy允許任何操作
該錯誤有點誤導,因為它似乎是跨源請求錯誤。 實際上,這只是rails控制器中的錯誤。 因此,如果您曾經將rails掛接到angular的后端並遇到此錯誤,則可能是不正確的rails代碼。 希望這可以幫助!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.