我正在尝试使用 google oauth 获取用户登录信息。登录后我已经获得了凭证(访问令牌),但我如何获取用户个人资料?这是我的代码:导出默认函数
我正在尝试使用 google oauth 获取用户登录信息。登录后我已经获得了凭证(访问令牌),但我如何获取用户个人资料?
这是我的代码:
export default function SignIn() {
const responseMessage = async (response) => {
const { credential } = response;
const accessToken = credential;
try {
await axios
.post("http://localhost:5000/api/auth/google", { accessToken })
.then((response) => console.log(response))
.catch((error) => console.log(error.response));
} catch (error) {
console.log("Error fetching user info:", error);
}
};
const errorMessage = (error) => {
console.log(error);
};
return (
<>
<Box sx={{ display: "flex", justifyContent: "center" }}>
<GoogleLogin onSuccess={responseMessage} onError={errorMessage} />
</Box>
</>
);
}
const { default: axios } = require("axios");
const express = require("express");
const router = express.Router();
router.post("/auth/google", async (req, res) => {
const { accessToken } = req.body;
try {
const response = await axios.get(
`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${accessToken}`
);
const userInfo = response.data;
res.status(200).json(userInfo);
} catch (error) {
res.status(400).json({ error: `Error fetching user info: ${error}` });
}
});
module.exports = router;
在我使用谷歌登录后,它会抛出
error: "Error fetching user info: AxiosError: Request failed with status code 401"