javascript - 如果我从前端(React)获取(或发送请求)但通过 Postman Works 获取,则 Passport.js req.user 未定义或空字符串
问题描述
我已经阅读了 SO 上的所有 req.user undefined 帖子,但是 3 天后我还没有找到解决方案,所以请不要为另一个 req.user undefined 问题而生气。
我已经设置了一个普通的 Passport.js 本地用户身份验证。从注册到登录再到注销,一切都可以完美运行,除非我尝试从前端获取用户/用户会话。但是通过 Postman 获取(或请求)用户/用户会话工作得很好,我得到了完美的显示,甚至服务器控制台。记录我的用户信息而不是未定义,这与我尝试从前端获取它时不同。
在过去的 3 天里,我无数次地修改了我的 Cors & Fetch Code,我真的束手无策。
<-- 后端(节点/Express)代码-->
// App
const app: Application = express();
app.use(express.urlencoded({ extended: true }))
app.use(express.json());
app.use(cors({ origin: 'http://localhost:3000', credentials: true }));
// I've even tried to include methods: "GET,HEAD,PUT,PATCH,POST,DELETE" with NO success.
// I've tried with and without origin or credentials.
// Express Session
app.use(session({
// secret: process.env.SESSION_SECRET
secret: 'whatever the secret is',
resave: false,
store: new pgSessionStore({
pool: pool,
tableName: 'session'
}),
saveUninitialized: true,
cookie: { maxAge: 365 * 24 * 60 * 60 * 1000 } //One year
}))
// Initialize passport & session
app.use(passport.initialize());
app.use(passport.session());
// Auth
initializePassport(passport);
// Routes
app.use(mountRoutes);
<-- 前端 (React.js) 代码--> 我在 Fetch、Axios 和 Cors 可以提供的不同“配置”变体中尝试了 Axios 和 Fetch。
const requestUser = () => {
fetch("http://localhost:3001/users", {
method: "GET",
mode: 'cors',
credentials: 'include',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
}).then((res) => console.log(res)).catch(err => console.log(err))
const config = {
withCredentials: true,
headers: {
'Content-Type': 'application/json',
},
};
const url = 'http://localhost:3001/users'
const getUser = () => {
axios.get(url, config).then((res) => {
console.log(res.data);});
}
我真的很机智,我希望有人能帮助我。也许我只是在 3 天后无法看到树前的森林。提前致谢。
解决方案
推荐阅读
- c++ - std::isspace 是 C++ 中 std::isgraph 的对立面吗(语言环境版本)
- javascript - Redux、useSelector 和 map:改变状态后,map() 不会改变内容
- excel - 如何将代码应用于以下所有行
- python - 如何在 Python 中处理异常处理
- c# - 如何将 WPF 支持添加到 .NET 5 Winforms 项目
- spotipy - 使用 spotipy 获得可舞性和效价
- scala - Spark SQL - 查找乘客去过的最多国家
- firebase - 尝试从我的集合中获取数组数据时遇到问题
- mysql - Munin MySQL插件的未知图形错误
- string - MATLAB:计算表列中出现的字符串