最近我在一个组织工作。他们告诉我使用 oauth 和 jwt,没有本地身份验证。我使用了 Passport-google-oauth20 和 jsonwebtoken 包。我在前端反应部分遇到问题。如何使用fetch或axios从后端获取数据?
这是我的代码 服务器.js
app.get(
"/auth/google",
passport.authenticate("google", {
scope: ["profile", "email"],
})
);
app.get(
"/auth/google/callback",
passport.authenticate("google", { session: false }),
generateAccessToken,
function (req, res) {
if (req.token) {
const email = req.user.email;
const token = req.token;
return res.status(200).json({ email, token });
} else res.status(400).json({ message: "Something went wrong" });
}
);
token.js
exports.generateAccessToken = (userId) => {
const token = jwt.sign({ _id: userId }, process.env.JWT_SECRET, {
expiresIn: "1h",
issuer: process.env.JWT_ISSUER,
});
return token;
};
使用登录挂钩
export const useLogin = () => {
const [error, setError] = useState(null);
const [isLoading, setIsLoading] = useState(null);
const { dispatch } = useAuthContext;
const login = async () => {
setIsLoading(true);
setError(null);
const response = await fetch("localhost:4000/auth/google/callback", {
method: "GET",
credentials: "include",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
"Access-Control-Allow-Credentials": true,
},
});
const json = await response.json;
if (!response.ok) {
setIsLoading(false);
setError(json.error);
}
if (response.ok) {
localStorage.setItem("user", JSON.stringify(json));
dispatch({ type: "LOGIN", payload: json });
setIsLoading(false);
}
};
return { login, isLoading, error };
};
如何从后端获取用户邮件和令牌? 我知道我可以通过
window.open("localhost:4000/auth/google,"_self")
访问该页面,但是我如何检索数据。
您可以通过标头或网址参数发送:
router.get("/google/callback",passport.authenticate("google", {
session: false,
failureRedirect: "api/auth/login/failed",
}),async (req, res) => {
console.log({ userInCallback: req.user });
res.redirect(`http://localhost:3000/mail=req.user.email`);
}