برنامه نویسی

خطای Google Login OAuth: 401 در React Frontend

Summarize this content to 400 words in Persian Lang

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cflrqbnar8aef26t7lv3.png)Login.jsx
import{ useState } from “react”;
import { GoogleOAuthProvider, GoogleLogin } from “@react-oauth/google”;
import { FaFacebook, FaLinkedin } from “react-icons/fa”;
import { Link, useNavigate } from “react-router-dom”;
import { facebookLogin, linkedinLogin } from “../../utils/api”;
import logo from “../../assets/logo.png”; // Ensure the correct path to your logo

const clientId = “xxxx”; // Replace with your actual Google client ID

const Login = () => {
const [error, setError] = useState(“”);
const navigate = useNavigate();

const handleGoogleSuccess = async (credentialResponse) => {
try {
const token = credentialResponse.credential;

// Fetch user profile info from Google
//const userInfoResponse = await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${token}`, {
const userInfoResponse = await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?token=${token}`);
if (!userInfoResponse.ok) {
throw new Error(`Failed to fetch user info: ${userInfoResponse.statusText}`);
}
const userInfo = await userInfoResponse.json();
console.log(“User info:”, userInfo);

// Send user info to the backend
const response = await fetch(“http://localhost:3000/auth/gxxxxx”, {
method: “POST”,
headers: {
“Content-Type”: “application/json”,
},
body: JSON.stringify({
firstName: userInfo.given_name || “”,
lastName: userInfo.family_name || “”,
email: userInfo.email || “”,
}),
});

if (!response.ok) {
throw new Error(`Backend responded with status: ${response.status}`);
}

const data = await response.json();
console.log(“Backend response:”, data);

if (data.token) {
localStorage.setItem(“token”, data.token);
navigate(“https://dev.to/”);
} else {
setError(data.message || “Google login failed”);
}
} catch (err) {
setError(err.message || “An error occurred during Google login”);
}
};

const handleGoogleFailure = () => {
setError(“Google login failed. Please try again.”);
};

return (

Login

{error && {error}}

Sign in with Facebook

Sign in with LinkedIn

Dont have an account?

Create one

);
};

export default Login;

وارد حالت تمام صفحه شوید

از حالت تمام صفحه خارج شوید

سلام تیمFront End: React.js. ورود به سیستم Google OAuthBackend: Express API Endpointهر گونه پیشنهاد یا بازخورد استقبال می شود. پیشاپیش ممنون

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/cflrqbnar8aef26t7lv3.png)Login.jsx
import{ useState } from "react";
import { GoogleOAuthProvider, GoogleLogin } from "@react-oauth/google";
import { FaFacebook, FaLinkedin } from "react-icons/fa";
import { Link, useNavigate } from "react-router-dom";
import { facebookLogin, linkedinLogin } from "../../utils/api";
import logo from "../../assets/logo.png"; // Ensure the correct path to your logo

const clientId = "xxxx"; // Replace with your actual Google client ID

const Login = () => {
  const [error, setError] = useState("");
  const navigate = useNavigate();

  const handleGoogleSuccess = async (credentialResponse) => {
    try {
      const token = credentialResponse.credential;

      // Fetch user profile info from Google
      //const userInfoResponse = await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?access_token=${token}`, {
      const userInfoResponse = await fetch(`https://www.googleapis.com/oauth2/v3/userinfo?token=${token}`);
      if (!userInfoResponse.ok) {
        throw new Error(`Failed to fetch user info: ${userInfoResponse.statusText}`);
      }
      const userInfo = await userInfoResponse.json();
      console.log("User info:", userInfo);

      // Send user info to the backend
      const response = await fetch("http://localhost:3000/auth/gxxxxx", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          firstName: userInfo.given_name || "",
          lastName: userInfo.family_name || "",
          email: userInfo.email || "",
        }),
      });

      if (!response.ok) {
        throw new Error(`Backend responded with status: ${response.status}`);
      }

      const data = await response.json();
      console.log("Backend response:", data);

      if (data.token) {
        localStorage.setItem("token", data.token);
        navigate("https://dev.to/");
      } else {
        setError(data.message || "Google login failed");
      }
    } catch (err) {
      setError(err.message || "An error occurred during Google login");
    }
  };

  const handleGoogleFailure = () => {
    setError("Google login failed. Please try again.");
  };

  return (

لوگو

Login

{error &&

{error}

}

Dont have an account? Create one

); }; export default Login;
وارد حالت تمام صفحه شوید

از حالت تمام صفحه خارج شوید

سلام تیم
Front End: React.js. ورود به سیستم Google OAuth
Backend: Express API Endpoint
هر گونه پیشنهاد یا بازخورد استقبال می شود. پیشاپیش ممنون

نوشته های مشابه

دیدگاهتان را بنویسید

نشانی ایمیل شما منتشر نخواهد شد. بخش‌های موردنیاز علامت‌گذاری شده‌اند *

دکمه بازگشت به بالا