Champer Wu Champer Wu - 8 months ago 22
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])

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


Activity Coffee JS

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

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?


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

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


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

(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!