reactjs 响应谷歌登录静默失败

ee7vknir  于 2023-03-12  发布在  React
关注(0)|答案(3)|浏览(122)
const onGoogleLoginFailure = () => {
    console.log("failed");
  };

const onGoogleLoginSuccess = useCallback((response) => {
    const idToken = response.tokenId;
    console.log("WHY ARE YOU LIKE THIS");
    fetch("/api/auth/", {
      method: "GET",
      headers: {
        Authorization: idToken,
      },
    }).then((res) => console.log(res));
    // .then((_) =>  navigate("/overview"))
  }, []);

  return isLoading ? null : (
    <Flex alignItems="center" justifyContent="center" h="100vh">
      <GoogleLogin
        clientId="tokenBOI" // your Google app client IDđ
        onSuccess={onGoogleLoginSuccess}
        onFailure={() => onGoogleLoginFailure}
        disabled={false}
        render={(renderProps) => {
          return (
            <Button onClick={renderProps.onClick}>
              Login
            </Button>
          );
        }}
      />
    </Flex>
  );

如前所述,上面的代码静默失败并触发onFailure。id标记有效,范围在一个组织内。选择帐户的提示打开,我选择帐户,提示关闭,然后什么也没发生。

bttbmeg0

bttbmeg01#

react-google-login包正在被弃用的过程中,这就是为什么认证过程失败。我面临着同样的问题,所以显然我们必须使用react-oauth/google包进行认证,所以这值得一看。检查https://www.npmjs.com/package/@react-oauth/google了解更多细节。

nhaq1z21

nhaq1z212#

试试这些

const LoginFailure = (response) => {
    console.log(response)
    swal('Login fail')
  }

并调用函数onFailure={登录失败}

v1l68za4

v1l68za43#

我有同样的问题,并没有改变尝试新的软件包:

import { useContext, useState } from "react";
import { FcGoogle } from "react-icons/fc";
import { MdVisibility } from "react-icons/md";
import { MdVisibilityOff } from "react-icons/md";
import { isEmpty, isEmail } from "../helper/validate";
import axios from "axios";
import { ToastContainer, toast } from "react-toastify";
import "react-toastify/dist/ReactToastify.css";
import Input from "../Input/Input";
import "./login.css";
import { AuthContext } from "../../context/AuthContext";
//import GoogleLogin from "react-google-login"; //deprecated
import { GoogleLogin } from '@react-oauth/google';

const initialState = {
  name: "",
  password: "",
};

const Login = () => {
  const [visible, setVisible] = useState(false);
  const [data, setData] = useState(initialState);
  const { email, password } = data;
  const { dispatch } = useContext(AuthContext);

  const handleChange = (e) => {
    setData({ ...data, [e.target.name]: e.target.value });
  };

  const handleClick = () => {
    setVisible(!visible);
  };

  const login = async (e) => {
    e.preventDefault();
    // check fields
    if (isEmpty(email) || isEmpty(password))
      return toast("Please fill in all fields.", {
        className: "toast-failed",
        bodyClassName: "toast-failed",
      });
    // check email
    if (!isEmail(email))
      return toast("Please enter a valid email address.", {
        className: "toast-failed",
        bodyClassName: "toast-failed",
      });
    try {
      await axios.post("/api/auth/signing", { email, password });
      localStorage.setItem("_appSignging", true);
      dispatch({ type: "SIGNING" });
    } catch (err) {
      toast(err.response.data.msg, {
        className: "toast-failed",
        bodyClassName: "toast-failed",
      });
    }
  };

  const googleSuccess = async (res) => {
    const token = res?.tokenId;
    try {
      await axios.post("/api/auth/google_signing", { tokenId: token });
      localStorage.setItem("_appSignging", true);
      dispatch({ type: "SIGNING" });
    } catch (err) {
      toast(err.response.data.msg, {
        className: "toast-failed",
        bodyClassName: "toast-failed",
      });
    }
  };

  const googleError = () => {
    toast("There was an error signing in, please try again later.", {
      className: "toast-failed",
      bodyClassName: "toast-failed",
    });
  };

  return (
    <>
      <ToastContainer />
      <form className="login" onSubmit={login}>
        <Input
          type="email"
          text="Email"
          name="email"
          handleChange={handleChange}
        />
        <Input
          name="password"
          type={visible ? "text" : "password"}
          icon={visible ? <MdVisibility /> : <MdVisibilityOff />}
          text="Password"
          handleClick={handleClick}
          handleChange={handleChange}
        />
        <div className="login_btn">
          <button type="submit">login</button>
          <GoogleLogin
            clientId={process.env.REACT_APP_G_CLIENT_ID}
            render={(renderProps) => (
              <button
                className="btn-alt"
                onClick={renderProps.onClick}
                disabled={renderProps.disabled}
              >
                sign in <FcGoogle />
              </button>
            )}
            cookiePolicy={"single_host_origin"}
            onSuccess={googleSuccess}
            onFailure={googleError}
          />
        </div>
      </form>
    </>
  );
};

export default Login;

相关问题