How do i add the authenticity token?

江枫思渺然 提交于 2019-12-05 20:00:34

问题


I recently switched to Google closure for a new project. I am having trouble adding the authenticity token to the headers in a ajax call. How do i go about it?

My Ajax snippet (using goog.net.XhrIo class):

var initialHTMLContent = superField[i].getCleanContents();

var data = goog.Uri.QueryData.createFromMap(new goog.structs.Map({
  body: initialHTMLContent
 }));

 goog.net.XhrIo.send('/blogs/create', function(e) {
    var xhr = /** @type {goog.net.XhrIo} */ (e.target);
    alert(xhr.getResponseXml());
 }, 'POST', data.toString(), {
    'Accept' : 'text/xml'
            });

Using rails in the backend.

UPDATE:

Log:

Processing BlogsController#create (for 127.0.0.1 at 2010-06-29 20:18:46) [PUT]
  Parameters: {"authenticity_token"=>""}

ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):


Rendered rescues/_trace (272.4ms)
Rendered rescues/_request_and_response (1.2ms)
Rendering rescues/layout (unprocessable_entity)

回答1:


Somewhere in a rails view (.html.erb file) you can set a js variable like this:

window._token = '<%= form_authenticity_token %>';

And then append it in your call:

 goog.net.XhrIo.send('/blogs/create?authenticity_token=' + window._token, function(e) {
    var xhr = /** @type {goog.net.XhrIo} */ (e.target);
    alert(xhr.getResponseXml());
 }, 'POST', data.toString(), {
    'Accept' : 'text/xml'
            });



回答2:


Rails now automatically adds a meta tag for it, so then in your page javascript you can use:

 token = $( 'meta[name="csrf-token"]' ).attr( 'content' )


来源:https://stackoverflow.com/questions/3141041/how-do-i-add-the-authenticity-token

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!