Google OAuth2,请求失败,状态码为400(错误请求)

时间:2020-10-29 14:21:18

标签: node.js reactjs oauth-2.0 google-oauth

React-google-login返回一个错误的请求,没有太多信息,状态码为400。

我的服务器代码

// Google OAuth client API
const client = new OAuth2Client(process.env.GOOGLE_CLIENT);
exports.googleLoginController = (req, res) => {
// Get token from request
const { idToken } = req.body;
// verify token
client.verifyIdToken({
     idToken,
     audience: process.env.GOOGLE_CLIENT
}).then(response => {
     const { email_verified, name, email } = response.getPayload;
     // Check if email verified
     if (email_verified) {
         let password = email + process.env.JWT_SECRET;
                 //Create user object with this email
                 user = new User({ name, email, password });
                 user.save((err, data) => {
                     if (err) {
                         console.log(err);
                         return res.status(400).json({
                             error: errorHandler(err)
                         });
                     }
                     //  if no error, generate token
                     const token = jwt.sign(
                         { _id: data._id },
                         process.env.JWT_SECRET,
                         { expiresIn: '7d' }
                     );
                     return res.json({
                         token,
                         user: { _id, email, name, role }
                     });
                 });
     }
 });
}

客户

// Send google token
const sendGoogleToken = (tokenId) => {
    axios.post(`${process.env.REACT_APP_API_URL}/google/login`, {
        idToken: tokenId
    }).then(res => {
            informParent(res);
        }).catch(err => {
            console.log("Google Login Error: ", err);
            toast.error("Google login error");
        });
    }

    // If success, we need to authenticate user and redirect
    const informParent = (response) => {
        authenticate(response, () => {
            isAuth() && isAuth.role === 'admin'
                ? history.push('/admin')
                : history.push('/normal');
        });
    }

我尝试查看this,但无法解决我的问题。

如果有人可以指导我如何解决此问题。我的代码或其他任何问题吗? 预先感谢。.

0 个答案:

没有答案