将参数从angularjs传递给rails项目

时间:2014-07-19 10:18:17

标签: ruby-on-rails angularjs

我有2个项目:1.rails项目。 2.angularjs项目。 在rails项目中,我有一个由widget创建的scaffold模型。现在我想从angularjs项目获取小部件数据并将数据发布到rails控制器。 为此,我在angularjs项目中创建了2 textfield,当我完成该字段时,我通过以下代码发布数据:

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)
    }
})

index.html

<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)">

在rails项目中,我有以下代码: widgets_controller.rb

skip_before_filter :verify_authenticity_token  
  # 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

config/routes.rb

match '/widgets' => 'widgets#create', via: :options

当我将widget数据从angularjs项目发送到rails控制器时,我在服务器日志中得到以下错误:

Started OPTIONS "/widgets" for 127.0.0.1 at 2014-07-19 14:29:20 +0430
Processing by WidgetsController#create as */*
Completed 400 Bad Request in 0ms

ActionController::ParameterMissing (param not found: widget):
  app/controllers/widgets_controller.rb:75:in `widget_params'
  app/controllers/widgets_controller.rb:29:in `create'
Chrome浏览器中的

及以下错误:

Failed to load resource: the server responded with a status of 400 (Bad Request) http://localhost:3000/widgets
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. 

问题出在哪里?如何解决这个错误?

1 个答案:

答案 0 :(得分:0)

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. 

此消息说明了该怎么做。在您的请求和响应中添加以下标题

同样检查这个问题,可能会在这里回答 Set a request header in JavaScript