javascript - Angularjs Rails-起源 http ://localhost:9000 is not allowed by Access-Control-Allow-Origin.

标签 javascript ruby-on-rails rest angularjs

我刚刚开始使用 angularjs,并且使用 Rails 作为后端 api。我已经成功设置了 Angular rails 资源( https://github.com/FineLinePrototyping/angularjs-rails-resource )和机架 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]
          )

    }

这是使用 Angular 轨资源的节日工厂

应用程序/脚本/服务/Festival.coffee

'use strict'

angular.module('MFNApp')
  .factory 'Festival', (railsResourceFactory) ->
    railsResourceFactory
      url: 'http://localhost:3000/festivals', 
      name: 'festival'

这是 View

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) 的请求,或者您可以按照此处所述 Allow anything through CORS Policy 为所有域打开它。

关于javascript - Angularjs Rails-起源 http ://localhost:9000 is not allowed by Access-Control-Allow-Origin.,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19009544/

相关文章:

javascript - 多个日期选择器/Mindate Bootstrap Angular Datepicker

javascript - 我的表单验证无法正常工作

ruby-on-rails - rails 4 在 postgres 的多个列上选择不同的位置和限制

.net - 是否可以连接到 WCF 缓存提供程序?

rest - 如何将 Swagger OpenAPI 规范添加到 Spring Boot 项目中?

javascript - 正则表达式 - 不重复句号、逗号和连字符

提交时 JavaScript 表单验证。

ruby-on-rails - 我的 CkEditor 在 Active Admin 中看起来不太好

ruby-on-rails - 管理员和用户的 Pundit- Index 方法

java - 测试失败时 Rest Assured Exception