You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Native无法获取登录用户详情的问题排查求助

问题:React Native无法获取Laravel接口返回的用户详情

尝试在React Native中加载当前登录用户的详情,但未接收到任何数据,用Postman测试/api/user-profile接口时返回{}。


Laravel端相关代码

登录接口方法

public function loginUser(Request $request)
{
    try {
        $validateUser = Validator::make($request->all(), [
            'email' => 'required|email',
            'password' => 'required',
        ]);

        if ($validateUser->fails()) {
            return response()->json([
                'status' => false,
                'message' => 'Validation error',
                'errors' => $validateUser->errors(),
            ], 401);
        }

        if (!Auth::attempt($request->only(['email', 'password']))) {
            return response()->json([
                'status' => false,
                'message' => 'Email & Password do not match our records.',
            ], 401);
        }

        $user = auth()->user();

        return response()->json([
            'status' => true,
            'message' => 'User Logged In Successfully',
            'user' => $user,
            'token' => $user->createToken("API TOKEN")->plainTextToken,
        ], 200);
    } catch (\Throwable $th) {
        return response()->json([
            'status' => false,
            'message' => $th->getMessage(),
        ], 500);
    }
}

用户详情接口方法

public function userProfile()
{
    return response()->json(auth()->user());
}

React Native端请求代码

useEffect(() => {
    const fetchUserData = async () => {
      try {
        const token = await AsyncStorage.getItem('userToken');

        if (!token) {
          console.error('User token not found in AsyncStorage');
          return;
        }

        const response = await fetch('https://dev.myexample.com/api/user-profile', {
          method: 'GET',
          headers: {
            'Authorization': `Bearer ${token}`,
          },
        });

        if (response.ok) {
          const responseData = await response.json();
          setUserData(responseData.user); // Update the user data state with the response
        } else {
          console.error('Failed to fetch user data. Status:', response.status);
        }
      } catch (error) {
        console.error('Error fetching user data:', error);
      }
    };

    fetchUserData();
  }, []);

解决方向

  • 检查路由认证中间件:确认user-profile路由是否使用了auth:sanctum中间件(因为登录接口用了createToken,默认依赖Sanctum认证)。如果路由未配置该中间件,或者错误使用了auth:api(未配置Passport),会导致认证失败,auth()->user()返回null,最终返回空对象。
  • 修正接口返回格式:当前userProfile直接返回用户对象本身,但React Native代码尝试读取responseData.user,即使认证成功也会取不到数据。需要修改接口返回:
    return response()->json(['user' => auth()->user()]);
    
  • 验证User模型配置:确保User模型引入了HasApiTokens trait(Sanctum认证必需),否则生成的token无法正常完成认证流程。
  • 查看Laravel日志:检查storage/logs/laravel.log中的请求日志,查找认证相关的错误信息,快速定位问题根源。
  • Postman测试校验:测试时确保请求头的Authorization格式为Bearer [登录接口返回的plainTextToken],token无截断或输入错误。

内容的提问来源于stack exchange,提问作者user20521476

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.10 14:55:00