【问题标题】:HTTP:No 'Access-Control-Allow-Origin' header is present on the requested resourceHTTP:请求的资源上不存在“Access-Control-Allow-Origin”标头
【发布时间】:2014-12-01 14:15:57
【问题描述】:

我有 2 个项目:

  1. rails 项目。

  2. angularjs 项目。

现在我想在 angularjs 项目中使用 rails 模型。我有一个由scaffold 创建的widget 模型。现在我想通过httppost 方法将一个新的widget 从angularjs 项目添加到rails 项目。为此,我有以下代码:

angularproject/js/app.js:

var app = angular.module("app",[]);

app.controller("AppCtrl", function($http){
    app = this;
    $http.get("http://localhost:3000/widgets.json")
        .success(function(data){
            console.log(data)
            app.peaple = data;
        })
    app.addWidget = function (widget){
        $http.post("http://localhost:3000/widgets",widget)
    }
})

angularproject/index.html:

<!doctype html>
<html>
<head>
    <script src="js/angular.min.js"></script>
    <script src="js/app.js"></script>
</head>
<body ng-app="app" ng-controller="AppCtrl as app">
<!--add new widget by post method in http-->
<input type="text" ng-model="app.widget.name">
<input type="text" ng-model="app.widget.price">
<input type="button" ng-click="app.addWidget(app.widget)">
<!--display all widget-->
<ul>
    <li ng-repeat="widget in app.peaple">
        {{widget.name}}<br/>{{widget.price}}
    </li>
</ul>
</body>
</html>

我将以下代码添加到 rails 项目: application_controller.rb

#add this line for allow to get widget json
after_filter :cors_set_access_control_headers
  private
  def cors_set_access_control_headers
    headers['Access-Control-Allow-Origin'] = '*'
    headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS'
    headers['Access-Control-Allow-Headers'] = %w{Origin Accept Content-Type X-Requested-With X-CSRF-Token}.join(',')
    headers['Access-Control-Max-Age'] = "1728000"
  end

widgets_controller.rb:

# GET /widgets
# GET /widgets.json
  def index
    @widgets = Widget.all
  end
# POST /widgets
# POST /widgets.json
  def create
    @widget = Widget.new(widget_params)

    respond_to do |format|
      if @widget.save
        format.html { redirect_to @widget, notice: 'Widget was successfully created.' }
        format.json { render action: 'show', status: :created, location: @widget }
      else
        format.html { render action: 'new' }
        format.json { render json: @widget.errors, status: :unprocessable_entity }
      end
    end
  end

通过这段代码,我可以获得widget json 并显示给用户,但是当我完成新的widget 字段并发布到rails 控制器时,我在控制台上收到以下错误:

XMLHttpRequest cannot load http://localhost:3000/widgets. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:63343' is therefore not allowed access. 

rails 服务器日志中出现以下错误:

Started OPTIONS "/widgets" for 127.0.0.1 at 2014-07-18 18:02:05 +0430

ActionController::RoutingError (No route matches [OPTIONS] "/widgets"):
  actionpack (4.0.3) lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
  actionpack (4.0.3) lib/action_dispatch/middleware/show_exceptions.rb:30:in `call'
  railties (4.0.3) lib/rails/rack/logger.rb:38:in `call_app'
  railties (4.0.3) lib/rails/rack/logger.rb:20:in `block in call'
  activesupport (4.0.3) lib/active_support/tagged_logging.rb:67:in `block in tagged'
  activesupport (4.0.3) lib/active_support/tagged_logging.rb:25:in `tagged'
  activesupport (4.0.3) lib/active_support/tagged_logging.rb:67:in `tagged'
  railties (4.0.3) lib/rails/rack/logger.rb:20:in `call'
  actionpack (4.0.3) lib/action_dispatch/middleware/request_id.rb:21:in `call'
  rack (1.5.2) lib/rack/methodoverride.rb:21:in `call'
  rack (1.5.2) lib/rack/runtime.rb:17:in `call'
  activesupport (4.0.3) lib/active_support/cache/strategy/local_cache.rb:83:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  actionpack (4.0.3) lib/action_dispatch/middleware/static.rb:64:in `call'
  rack (1.5.2) lib/rack/sendfile.rb:112:in `call'
  railties (4.0.3) lib/rails/engine.rb:511:in `call'
  railties (4.0.3) lib/rails/application.rb:97:in `call'
  rack (1.5.2) lib/rack/lock.rb:17:in `call'
  rack (1.5.2) lib/rack/content_length.rb:14:in `call'
  rack (1.5.2) lib/rack/handler/webrick.rb:60:in `service'
  C:/Ruby200-x64/lib/ruby/2.0.0/webrick/httpserver.rb:138:in `service'
  C:/Ruby200-x64/lib/ruby/2.0.0/webrick/httpserver.rb:94:in `run'
  C:/Ruby200-x64/lib/ruby/2.0.0/webrick/server.rb:295:in `block in start_thread'


  Rendered C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.0ms)
  Rendered C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/routes/_route.html.erb (1.0ms)
  Rendered C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/routes/_table.html.erb (1.0ms)
  Rendered C:/Ruby200-x64/lib/ruby/gems/2.0.0/gems/actionpack-4.0.3/lib/action_dispatch/middleware/templates/rescues/routing_error.erb within rescues/layout (38.0ms)

问题出在哪里?如何向angularjs 项目添加权限以在数据库中添加新的widget

【问题讨论】:

    标签: ruby-on-rails angularjs


    【解决方案1】:

    您的 Rails 应该允许 http“选项”方法(预检请求)。要了解有关预检请求的更多信息,请查看link

    或者查看 rack-cors gem,它允许你像路由文件一样配置它

    https://github.com/cyu/rack-cors

    【讨论】:

      猜你喜欢
      • 2013-11-29
      • 2014-07-28
      • 2014-01-19
      • 2013-12-07
      相关资源
      最近更新 更多