繁体   English   中英

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

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM