React使用GoogleOAuthProvider仍报缺少client_id参数问题及解决
React集成Google OAuth遇"Missing required parameter client_id."错误的解决
问题
在React应用中集成Google OAuth功能时,无论怎么调整配置,一直收到Missing required parameter client_id.的错误提示。
已完成以下排查步骤:
- 环境变量中配置了正确的Google客户端ID
- 尝试过直接硬编码客户端ID替代环境变量
- Google云控制台已正确配置允许localhost访问
涉及代码
index.js
import React from 'react'; import ReactDOM from 'react-dom/client'; import './index.css'; import App from './App'; import { GoogleOAuthProvider } from "@react-oauth/google"; import {BrowserRouter} from 'react-router-dom'; const root = ReactDOM.createRoot(document.getElementById('root')); root.render( <React.StrictMode> <GoogleOAuthProvider clientId={process.env.REACT_APP_GOOGLE_CLIENT_ID}> <BrowserRouter> <App /> </BrowserRouter> </GoogleOAuthProvider> </React.StrictMode> );
Google登录按钮组件
import React from "react"; import { useNavigate } from "react-router"; import Cookies from "universal-cookie"; import { useGoogleLogin } from "@react-oauth/google"; import google from "../../../assets/google.svg"; import SignUpButton from "../../../components/SignUpButton/SignUpButton"; const GoogleAuth = () => { const googleLogin = useGoogleLogin({ flow: 'auth-code', onSuccess: async (codeResponse) => { console.log(codeResponse); const response = await fetch('http://localhost:3001/auth/google', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ code: codeResponse.code }) }); const tokens = await response.json(); console.log(tokens); }, onError: errorResponse => console.log(errorResponse), }); return ( <SignUpButton text="Sign up with Google" image={google} bgColor="bg-gray-800" onClick={() => googleLogin} /> ); }; export default GoogleAuth;
最终解决方案
排查后发现项目其他代码中错误引入并使用了GoogleAuthProvider(与@react-oauth/google提供的GoogleOAuthProvider混淆),将这个错误的Provider实例移除后,问题得到解决。
内容的提问来源于stack exchange,提问作者24Chromosones
相关产品推荐
相关产品推荐

