Rails Render JSON - Session Lost?

余生颓废 提交于 2020-01-14 09:43:12

问题


i am trying to make some Ajax calls to an controller which responds with JSON.

if session[:user]
  render :json => "Some Data"
else
  render :json => "You are not logged in"
end

The first time this action gets called by an authed user everything is ok and session[:user] is != nil. The second time it gets called it is nil!

So it seems like rails is loosing it's session as soon as i do render :json. I figured out that within the first call rails overrides the *_session-cookie with a new one. As consequence of that rails doesn't know about the initial, authed, session.

If i don't render the response as JSON everything works fine.

How to force rails to set the same sessionid in JSON rendered pages as in normal views?


回答1:


After six days of searching I finally made it:

Seems like rails destroys the session because of the missing X-CSRF-Token Header. I am adding this header now in in the ajaxSend Hook of JQuery:

$(document).ajaxSend(function(e, xhr, options) {
  var sid = $("meta[name='csrf-token']").attr("content");
  xhr.setRequestHeader("X-CSRF-Token", sid);
});

It's working as expected now.




回答2:


I put that in beforeSend method:

function goAjax(urlAddress,dataObject,successFunction,errorFunction){
        $.ajax({
              type: "POST",
              url: urlAddress,
              beforeSend: function ( xhr ) {
                    xhr.setRequestHeader("X-CSRF-Token", $('meta[name=csrf-token]').attr('content'));
              },
              dataType: "json",
              contentType: "application/json; charset=utf-8",
              processData: false,
              data: JSON.stringify(dataObject),
              context: document.body,
              success: function(data,status){ successFunction(data,status);},
              error: function(data,status){ errorFunction()}
        });
    }

works great if you don't need to use other way of ajax request(in this way you should add beforeSend to all ajax requests)



来源:https://stackoverflow.com/questions/8511695/rails-render-json-session-lost

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