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

如何通过PassportJs将用户信息获取并展示到前端

解决PassportJS Google Auth前端展示用户信息问题

一、修正前端Google登录跳转逻辑

原代码中google函数跳转了错误的路由,应该指向后端用于触发Google授权的/auth/google路由,而非回调地址:

const google = () => {
  window.open("http://localhost:4000/auth/google", "_self");
};

二、修复useEffect中的请求逻辑

原代码存在语法错误(dispatch位置错误)和数据取值错误,修正后如下:

useEffect(() => {
  dispatch({ type: "LOGIN_START" });
  fetch(`http://localhost:4000/login/success`, {
    method: 'GET',
    credentials: 'include',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/json',
    },
  })
  .then((response) => {
    if (response.status === 200) return response.json();
    throw new Error('failed to authenticate user');
  })
  .then((responseJson) => {
    // 后端返回的用户数据在responseJson.user字段中
    dispatch({ type: "LOGIN_SUCCESS", payload: responseJson.user });
  })
  .catch((error) => {
    dispatch({ type: "LOGIN_FAILURE" });
    console.error("Failed to authenticate user", error);
  });
}, []);

三、确保后端配置CORS支持跨域凭证

在后端主文件(如app.js)中配置CORS,允许前端域名并开启凭证传递:

const cors = require('cors');

app.use(cors({
  origin: "http://localhost:3000", // 前端项目地址
  credentials: true, // 允许携带Cookie等凭证
}));

四、在前端组件中展示用户信息

通过Context获取用户状态后,即可在组件中渲染用户信息:

import { useContext } from 'react';
import { AuthContext } from './AuthContext'; // 替换为你的Context路径

const UserProfile = () => {
  const { user } = useContext(AuthContext);

  if (!user) {
    return <div>请登录</div>;
  }

  return (
    <div>
      <h2>欢迎回来,{user.displayName}</h2>
      <img src={user.profilePic} alt="用户头像" style={{width: '100px', borderRadius: '50%'}} />
      <p>邮箱:{user.email}</p>
      <p>姓名:{user.firstName} {user.lastName}</p>
    </div>
  );
};

export default UserProfile;

额外优化建议

  1. 简化后端deserializeUser逻辑:
passport.deserializeUser(async (id, done) => {
  try {
    const user = await User.findById(id);
    done(null, user);
  } catch (e) {
    done(new Error("Failed to deserialize an user"));
  }
});
  1. 确保后端启用Session中间件(Passport依赖Session存储用户信息):
const session = require('express-session');

app.use(session({
  secret: 'your-custom-secret-key', // 替换为你的密钥
  resave: false,
  saveUninitialized: false,
  cookie: { secure: false } // 开发环境设为false,生产环境需HTTPS并设为true
}));

// 必须在Session之后初始化Passport
app.use(passport.initialize());
app.use(passport.session());

内容的提问来源于stack exchange,提问作者sultan.h

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 18:09:26