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

生产环境移动端浏览器使用Axios获取用户数据失败问题

移动端浏览器无法通过Axios获取用户数据的问题

问题背景

本地开发环境及PC浏览器中,通过Axios从后端获取用户数据的逻辑完全正常,但在移动端浏览器中无法获取数据。

实现代码

全局用户Context

export const userContext = createContext({});
const Context = props => {

    const [userState, setUserState] = useState();

    useEffect(() => {
        axios.get(getProductionURL('/api/get-user'), { withCredentials: true })
            .then(res => {
                if (res?.data) {
                    setUserState(res.data);
                }
            })
            .catch(error => {
              console.log(error);
              alert('Error')
            });
    }, []);


  return (
    <userContext.Provider value={userState}>{ props.children }</userContext.Provider>
  )
}

export default Context


export function getProductionURL(endpoint) {
    const baseURL = process.env.NODE_ENV === 'production' ? 'https://car-share-ride-a7b2b849cd69.herokuapp.com' : 'http://localhost:3000';
    
    if (endpoint) return baseURL + endpoint;
    else return baseURL;
}

Profile页面(修改前)

const Profile = () => {
const myUserContext = useContext(userContext);
const navigate = useNavigate();
console.log(myUserContext);

return (
  <main>
    { myUserContext?.completedProfile === false && (
      {/* 未完成Profile的提示内容 */}
    )}

    {/* Navigator with profile image */}
    <Actions picture={myUserContext?.picture} />
  </main>
);
};

export default Profile;

Profile页面(修改后)

const Profile = () => {
const myUserContext = useContext(userContext);
const navigate = useNavigate();
console.log(myUserContext);

useEffect(() => {
if (myUserContext?.isAuthenticated === false) {
navigate('/login');
}
}, [myUserContext, navigate])

if (myUserContext === undefined) return <h1>Loading...</h1>

return (
  <main>
    { myUserContext?.completedProfile === false && (
      {/* 未完成Profile的提示内容 */}
    )}
    {/* Navigator with profile image */}
  </main>
);
};

后端接口

userRouter.get('/get-user', async (req: Request, res: Response, next: NextFunction) => {
try {
// 检查用户是否已认证
const isAuthenticated = req.isAuthenticated();

// 在调用.toObject()前检查req.user是否存在
const userObject = req.user ? (req.user as any).toObject() : {};
userObject.isAuthenticated = isAuthenticated;
userObject.customProperty = 'some value';

res.status(200).json(userObject);
} catch (error) {
next(error);
}
});

问题现象

修改Profile页面后,移动端浏览器控制台先打印undefined,之后能正常打印用户对象,但页面始终停留在Loading...状态,不会渲染后续内容。


排查与解决方案

  • 跨域Cookie配置检查
    移动端浏览器对跨域Cookie的限制更严格,后端必须配置:

    • Access-Control-Allow-Origin设为前端实际域名(不能用*)
    • Access-Control-Allow-Credentials: true
    • Cookie的SameSite属性设为None并开启Secure(仅HTTPS环境生效),确保移动端能正常传递认证Cookie。
  • Context初始状态修正
    将Context中userState的初始值从undefined改为null:

    const [userState, setUserState] = useState(null);
    

    同步修改Profile页面的加载判断:

    if (myUserContext === null) return <h1>Loading...</h1>
    

    避免初始状态与请求未完成状态混淆,确保状态更新时组件能触发重新渲染。

  • Axios错误信息细化
    在请求的catch块中打印详细错误信息,定位移动端具体报错:

    .catch(error => {
      console.log('请求错误详情:', error.response?.data, error.message);
      alert('数据获取失败,请稍后重试');
    });
    
  • 组件包裹验证
    确认Profile组件被Context Provider正确包裹,不存在多层Provider或未包裹的情况,保证Context状态能正常传递。


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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 11:05:02