thinkphp8 session获取失败

1.登录时创建sesion,存入user_id

<?php
namespace app\controller;

use think\annotation\route\Route;
use app\BaseController;
use think\facade\Log;
use think\facade\Request;
use app\model\UserModel;

class UserController extends BaseController
{
    //创建userModel对象
    protected $userModel;

    public function __construct(UserModel $userModel)
    {
        $this->userModel = $userModel;
    }
    #[Route('POST','user/login')]
    public function login()
    {
        try {
            $username = Request::param('username');
            $password = Request::param('password');
            $user = $this->userModel->login($username, $password);
            if ($user != null) {
                session('user_id',$user['user_id']);
                return json(['code' => 0, 'msg' => '登录成功','session'=>session('user_id')]);
            } else
                return json(['code' => -1, 'msg' => '用户名或密码错误']);
        } catch (\Exception $e) {
            return json(['error' => $e->getMessage()]);
        }
    }

    //创建对象
  public function create()
    {
        try {

            $userId = session('user_id');
            $sessionData = session();
            Log::info('Session data:', $sessionData);
            $data = [
                'login_name' => Request::param('loginName'),
                'name' => Request::param('name'),
                'password' => md5(Request::param('password')),
                'email' => Request::param('email'),
                //从session获取是谁登录创建了新对象
                'operator_id' => $userId
            ];
            $result = $this->userModel->createUser($data);
            if ($result) {
                return json(['success' => true,'session'=>$userId]);
            } else {
                return json(['success' => false, 'message' => 'Failed to add user','session'=>$userId]);
            }
        } catch (\Exception $e) {
            return json(['error' => $e->getMessage()]);
        }
    }

2.app/middleware.php文件中已经解除了Session初始化的注释,登录功能运行之后runtime/session目录下生成新的session文件,存储内容为登录时的user_id。当运行create()方法时无法获取到session中存储的user_id。

thinkphp8 session获取失败

thinkphp8 session获取失败

唐章明
最佳答案
$.ajax({
    ...
    xhrFields: {
        withCredentials: true // 设置这个属性以允许跨域请求时携带凭证(如Cookie)
    },
   ...
});
6个月前 评论
north_door (楼主) 6个月前
讨论数量: 9

记录日志的id设置为自增,报错是不是自增并且必填就必须把id设置上去

6个月前 评论
north_door (楼主) 6个月前
deatil (作者) 6个月前
north_door (楼主) 6个月前
deatil (作者) 6个月前
north_door (楼主) 6个月前

我写了一个简单的案例重现了我遇到的问题:

class UserController extends BaseController
{
    protected $userModel;

    public function __construct(UserModel $userModel)
    {
        $this->userModel = $userModel;
    }

    public function login()
    {
        try {
            $username = Request::param('username');
            $password = Request::param('password');

            $user = $this->userModel->login($username, $password);
            if ($user) {
                //创建session
                session('user', $username);
                return json(['code' => 0, 'msg' => '登录成功', 'session' => session('user')]);
            } else {
                return json(['code' => -1, 'msg' => '用户名或密码错误']);
            }
        } catch (\Exception $e) {
            return json(['error' => $e->getMessage()]);
        }
    }

     //获取session
    public function get(){
        $session = session('user');
        return Response::create($session, 'json');
    }
}

前端login.html主要代码:

file

index.html主要代码:

浏览器控制台输出:

6个月前 评论
唐章明
$.ajax({
    ...
    xhrFields: {
        withCredentials: true // 设置这个属性以允许跨域请求时携带凭证(如Cookie)
    },
   ...
});
6个月前 评论
north_door (楼主) 6个月前

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!