Angularjs Rails-原始http:// localhost:9000是Access-Control-Allow-Origin不允许的。

时间:2013-09-25 15:50:07

标签: javascript ruby-on-rails rest angularjs

我刚开始使用angularjs,我使用rails作为后端api。我已经成功设置了角度轨道资源(https://github.com/FineLinePrototyping/angularjs-rails-resource)和机架,以便从轨道获取数据。当我尝试保存节日时,我收到以下错误:

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>

2 个答案:

答案 0 :(得分:0)

您必须允许网络API支持来自该域(http://localhost:9000)的请求,或者您可以按照此处所述为所有域打开Allow anything through CORS Policy

答案 1 :(得分:0)

错误有点误导,因为它似乎是一个跨源请求错误。这实际上只是rails控制器中的一个错误。因此,如果您将rails作为后端连接到angular并遇到此错误,则可能只是错误的rails代码。希望这有帮助!