Champer Wu Champer Wu - 7 months ago 12
Ruby Question

Ruby On Rails Application with angularJS about AJAX

I'm new to angularJS and Rails,and I tried to building a Rails application with AngularJS

and now, I want to do a POST request to sent data insert database

Activity Controller

def create
@activity = Activity.new(params[:activity])

respond_to do |format|
if @activity.save
format.html {redirect_to activities_url}
format.json { render activities_url, status: :created, location: @activity}
end
end

end


Activity Coffee JS

app = module('activity', ['ngAnimate'])
app.controller 'FormCtrl', ($scope, $http) ->
config = {
header: {
'Content-Type': 'application/json'
}
}
@test = ->
$http.post('/activities.json', {title: 'test1'}, config).success (data, status) ->
console.log(data)
console.log(status)
return


Console log

Started POST "/activities.json" for ::1 at 2016-05-04 21:06:10 +0800
Processing by ActivitiesController#create as JSON
Parameters: {"title"=>"test1", "activity"=>{"title"=>"test1"}}
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 2ms (ActiveRecord: 0.0ms)


I created a button of ng-click to trigger test function but I got information like console log, How can I do to fix it?

Answer

There is a great answer here: Rails API design without disabling CSRF protection

The gist of it is that you can put the CSRF token in a cookie called XSRF-TOKEN like so:

# In my ApplicationController
after_filter :set_csrf_cookie

def set_csrf_cookie
  if protect_against_forgery?
    cookies['XSRF-TOKEN'] = form_authenticity_token
  end
end

You'll then have to overload the verified_request? method in your ApplicationController to load the token from where Angular will return it:

protected

def verified_request?
  super || valid_authenticity_token?(session, request.headers['X-XSRF-TOKEN'])
end

(read the link I included though.. there are caveats, but I think you want something like this anyway... basically your login actions shouldn't be protected against csrf, but other potentially destructive actions should. You could achieve this with skip_before_filter.)

I hope that helps!

Comments