首页 > 解决方案 > React + Express google Oauth 错误 - CORS 策略:请求的资源上不存在“Access-Control-Allow-Origin”标头

问题描述

我正在使用 react 和 node+express 制作简单的 google Oauth 登录按钮。反应服务器 - 3000 节点 - 5000

现在,我已经在 server.js 和 react index.js 中定义了登录路由,我正在对该路由发出 get 请求

服务器 app.js

app.get('/auth/google',
passport.authenticate('google', { scope: ['profile'] }));

app.get('/auth/google/welcome', 
passport.authenticate('google', { failureRedirect: '/erro' }),
function(req, res) {
  // Successful authentication, redirect home.
 
  res.redirect("/welcome");
  // res.send("Hello");
  
});

反应 index.js

 const url = "http://localhost:5000/auth/google";

 const handleit = async () => {
 const data = await Axios.get(url,{
  mode:"cors"
 })
 .then(function (response) {
 console.log(response.data);
 });


 };




 return (
 <div>
 <h2>Hello</h2>
 <button onClick={handleit}>Sign in </button>
 </div>
 );

}

在我的谷歌开发者控制台中,我已经为这两个端口定义了 javascript 源 URL 和回调 URL。每当我单击登录按钮时,它都会显示此错误

在 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3000%2Fauth%2Fgoogle%2Fwelcome&scope=profile&client_id=782132931351-lb3im7qg19k9fh7ml711meld1nugur5j.apps 访问 XMLHttpRequest来自源“http://localhost:3000”的 .googleusercontent.com'(从“http://localhost:5000/auth/google”重定向)已被 CORS 策略阻止:无“访问控制允许来源”请求的资源上存在标头。

我到处搜索,但无法删除此错误并获得 google 登录提示,请帮助

标签: node.jsreactjsoauth-2.0corsgoogle-oauth

解决方案


推荐阅读