You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React调用Google API获取userInfo时的CORS问题求助

解决@react-oauth/google隐式授权的CORS问题

先修正请求代码,移除错误请求头

你在axios请求里添加了Access-Control-Allow-Origin,这个字段是服务端返回给客户端的响应头,客户端发起请求时完全不需要设置它——这是触发预飞请求验证失败的直接原因之一。把这个字段删掉,修改后的代码如下:

const handleGoogleLogin = useGoogleLogin({
    onSuccess: async (tokenResponse) => {
      console.log(tokenResponse);
      const token = pathOr('', ['access_token'], tokenResponse)
      const userInfo = await axios.get(
        'https://www.googleapis.com/oauth2/v3/userinfo',
        { headers: { Authorization: `Bearer ${token}` } },
      );

      console.log("user",userInfo);
    },
    onError: errorResponse => console.log(errorResponse),
  });

配置谷歌OAuth授权域名(核心步骤)

谷歌OAuth仅允许已授权的域名发起跨域请求,这是解决CORS问题的关键:

  • 登录谷歌云控制台,找到你的OAuth 2.0客户端ID配置项
  • 在「授权的JavaScript来源」列表中,添加你的前端域名https://mywebsite:3000(本地开发需额外添加http://localhost:3000)
  • 保存配置,等待几分钟让设置生效

可选:直接用插件自带方式获取用户信息

@react-oauth/google本身支持直接返回用户基础信息,无需额外调用userinfo接口,能彻底规避CORS问题:

const handleGoogleLogin = useGoogleLogin({
    scope: 'email profile', // 声明需要获取的用户信息权限
    fetch_basic_profile: true,
    onSuccess: (tokenResponse) => {
      // 直接从tokenResponse中获取用户信息
      console.log("user info", tokenResponse.profileObj);
    },
    onError: errorResponse => console.log(errorResponse),
  });

内容的提问来源于stack exchange,提问作者Muhammad Amir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.21 05:15:31