当我们在 Laravel 中使用 ajax 或 fetch 或 axios 或 xmlHttpRequest 发送请求时,会话不存在

问题描述

当我使用方法 post 发送请求 ajax 时。我想在后端检查我的会话。不存在吗??!! 我,我尝试任何方式:使用 ajax(jquery) 或使用 axios 或使用 fetch 或使用 xmlHttpRequest 注意:我,我也在任何请求中添加 csrf_token。

//this cod worked when i,m not use ajax request.but in ajax request not worked
if($session=session('testSession')){
    return $session;
}
$session=session(['testSession'=>random_int(12,23)]);
return $session;

解决方法

试试这个代码:

use Session;

if (Session::has('testSession')){
   return Session::get('testSession');
}else{
   Session::put('testSession',123456);
   return Session::get('testSession');
}