简体   繁体   中英

JSON request to Rails backend issue?

So within the ApplicationController class protect_from_forgery with: :null_session is invoked.

The Admin class inherits ApplicationController .

Thoughts as to why Can't verify CSRF token authenticity might have been thrown after a request mapped to Admin::LandingPagePhotosController#update ?

Started PATCH "/admin/landing_page_photos/2" for 127.0.0.1 at 2015-02-16 16:44:29 -0500
  User Load (3.0ms)  SELECT  "users".* FROM "users"  WHERE ("users"."status" != 'deleted') AND "users"."id" = 2  ORDER BY "users"."id" ASC LIMIT 1
Processing by Admin::LandingPagePhotosController#update as JSON
  Parameters: {"landing_page_photo"=>{"position"=>"1"}, "id"=>"2"}
Can't verify CSRF token authenticity
   (0.7ms)  BEGIN
   (0.6ms)  COMMIT
Completed 401 Unauthorized in 26ms

I'm not familiar I understand what you mean by protect_from_forgery with: null_session

but you will need to pass the CSRF token as it is not sent with ajax request automatically unless you are serializing a form created with rails.

See this SO for a simple solution:

Rails Ajax Can't verify CSRF token Authenticity

Generally, for JSON APIs, you would do without the CSRF protection.

This is how I achieve it:

skip_before_filter :verify_authenticity_token,
                     if: Proc.new { |c| c.request.format == 'application/json' }

I would put that in whatever controller your JSON API controllers inherit from. I have an ApiController which I use.

Lastly, don't forget to end your requests with the .json like: example.com/api/v1/posts.json

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM