【发布时间】:2021-01-10 10:51:35
【问题描述】:
我有一个使用 React JS (http://localhost:3000/) 开发的前端和使用 express JS (http://localhost:5000/) 开发的后端
谷歌控制台详情
React 登录页面:点击使用 Google 登录
const _handleGoogleSignInClick = async () => {
window.open("http://localhost:5000/socialauth/google", "_self");
}
快递代码
app.use(express.json());
app.use(cookieSession({
name: "session",
maxAge: 24 * 60 * 60 * 1000,
keys:[keys.session.cookieKey]
}))
app.use(cookieParser());
app.use(passport.initialize());
app.use(passport.session());
app.use(
cors({
origin: "http://localhost:3000",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true
})
);
//routes
app.use(cors());
app.use("/auth", require("./routes/jwtAuth"));
app.use("/socialauth", socialAuth);
********************************************************
const CLIENT_HOME_PAGE_URL = "http://localhost:3000";
router.get('/google', passport.authenticate('google', { scope: ["profile"] }));
router.get('/google/callback', passport.authenticate('google', {
successRedirect: CLIENT_HOME_PAGE_URL,
failureRedirect: "/socialauth/login/failed"
}));
router.get("/login/success", (req, res) => {
console.log(req.user);
if (req.user) {
res.json({ true});
}
});
现在我已经成功地验证了来自 Google 的用户,passport JS 为用户创建了一个会话,并将用户重定向到前端,他们必须再次验证自己。此时前端尝试验证用户,服务器验证用户成功并返回true,但这并没有被前端捕获。因此,用户无法看到仪表板,因为状态保持为假...
fetch("http://localhost:5000/socialauth/login/success", {
method: "GET",
credentials: "include",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Credentials": true
}
})
.then(response => {
if (response.status === 200) return response.json();
throw new Error("failed to authenticate user");
})
.then(responseJson => {
console.log("responseJson is -====", responseJson);
setIsAuthenticated(true);
问题?
在从客户端访问 fetch("http://localhost:5000/socialauth/login/success" 时,我看到服务器可以成功识别用户并返回 true,但是在我的客户端我无法获取 JSON 响应。
错误详情
错误是 -==== TypeError: NetworkError 尝试获取资源时。桌面组件.js:62 跨域请求被阻止:同源策略不允许在“http://localhost:5000/socialauth/login/success”读取远程资源。 (原因:如果 CORS 标头“Access-Control-Allow-Origin”为“*”,则不支持凭据)
【问题讨论】:
标签: node.js reactjs express cors passport.js