尝试获取资源 Passport ReactJS 和 ExpressJS 时出现网络错误:CORS
NetworkError when attempting to fetch resource Passport ReactJS and ExpressJS : CORS
我有一个 front-end 使用 React JS (http://localhost:3000/) 开发的,我的后端使用 express JS (http://localhost:5000/)
google 控制台详细信息
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 为用户创建了一个 session 并将用户重定向到前端,在那里他们必须再次验证自己。此时,前端尝试验证用户,服务器成功验证用户并且returns true,但是前端没有捕获到。因此,用户看不到仪表板,因为状态仍然为 false...
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" 时,我看到服务器可以成功识别用户并且 returns 是的,但是我的客户端无法获得 JSON 响应。
错误详情
错误是 -==== 类型错误:尝试获取资源时出现网络错误。 DesktopComponent.js:62
Cross-Origin 请求被阻止:同源策略不允许读取位于“http://localhost:5000/socialauth/login/success”的远程资源。 (原因:如果 CORS header 'Access-Control-Allow-Origin' 为 '*',则不支持凭据)
编辑:问题是 app.use(cors())
覆盖
app.use(
cors({
origin: "http://localhost:3000",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true
})
)
使用带有凭据的 CORS 时,这是必需的
可以参考CORS credentials
这基本上是因为您的客户端正在发送带有 withCredentials
的请求,您需要将其设置为 false(或者更改服务器端的 Access-Control-Allow-Origin
)
我有一个 front-end 使用 React JS (http://localhost:3000/) 开发的,我的后端使用 express JS (http://localhost:5000/)
google 控制台详细信息
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 为用户创建了一个 session 并将用户重定向到前端,在那里他们必须再次验证自己。此时,前端尝试验证用户,服务器成功验证用户并且returns true,但是前端没有捕获到。因此,用户看不到仪表板,因为状态仍然为 false...
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" 时,我看到服务器可以成功识别用户并且 returns 是的,但是我的客户端无法获得 JSON 响应。
错误详情
错误是 -==== 类型错误:尝试获取资源时出现网络错误。 DesktopComponent.js:62 Cross-Origin 请求被阻止:同源策略不允许读取位于“http://localhost:5000/socialauth/login/success”的远程资源。 (原因:如果 CORS header 'Access-Control-Allow-Origin' 为 '*',则不支持凭据)
编辑:问题是 app.use(cors())
覆盖
app.use(
cors({
origin: "http://localhost:3000",
methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
credentials: true
})
)
使用带有凭据的 CORS 时,这是必需的
可以参考CORS credentials
这基本上是因为您的客户端正在发送带有 withCredentials
的请求,您需要将其设置为 false(或者更改服务器端的 Access-Control-Allow-Origin
)