I have 2 project: 1.rails project. 2.angularjs project.
In the rails project, I have a widget
model that I create by scaffold
. Now I want get widget data from angularjs project and post data to rails controller.
for this, I create 2 textfield
in angularjs project, when I complete the field, I post the data by below code:
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)">
In rails project, I have below code:
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
When I send widget data from angularjs project to rails controller, I get below error in server log:
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'
and below error in chrome browsers:
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.
Where is the problem? How can fix this errors?