rails - “WARNING: Can't verify CSRF token authenticity” for json devise requests

前端 未结 10 2165
终归单人心
终归单人心 2020-11-27 10:11

How can I retrieve the CSRF token to pass with a JSON request?

I know that for security reasons Rails is checking the CSRF token on all the request types (including

10条回答
  •  遥遥无期
    2020-11-27 10:27

    Indeed simplest way. Don't bother with changing the headers.

    Make sure you have:

    <%= csrf_meta_tag %>
    

    in your layouts/application.html.erb

    Just do a hidden input field like so:

    
    

    Or if you want a jquery ajax post:

    $.ajax({     
        type: 'POST',
        url: "<%= someregistration_path %>",
        data: { "firstname": "text_data_1", "last_name": "text_data2", "authenticity_token": "<%= form_authenticity_token %>" },                                                                                  
        error: function( xhr ){ 
          alert("ERROR ON SUBMIT");
        },
        success: function( data ){ 
          //data response can contain what we want here...
          console.log("SUCCESS, data="+data);
        }
    });
    

    Basically when you post your json data just add a valid authenticity_token field to the post data and the warning should go away...

提交回复
热议问题