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
相关产品推荐
相关产品推荐

