CORS问题从React应用程序>节点服务器>redirect到Google OAuth2身份validation发出AJAX请求

嗨,我一直在敲我的头研究这个过去2天没有运气。

这是我从React应用程序@localhost:3000尝试使用Google Oauth2 Passport策略进行身份validation时遇到的错误。 我运行一个单独的应用程序与本地主机上的节点/快递服务器:3001。

XMLHttpRequest无法加载http:localhost:3001 / api / auth / google / login。 从“http:localhost:3001 / api / auth / google / login”redirect到“https:accounts.google.com/o/oauth2/v2/auth?response_type = code&redirect_uri = http%3A%2F%2Flocalhost%3A3001%2Fapi %2Fauth%2Fgoogle%2Fcallback&scope = https%3A%2F%2Fmail.google.com&client_id = ***。apps.googleusercontent.com'has been blocked by CORS policy:No'Access-Control-Allow-Origin'header is present on请求的资源。 原因'http:localhost:3000'因此不被允许访问。

createError.js:16 

未被捕获(承诺)错误:在XMLHttpRequest.handleError的createError(createError.js:16)处的networking错误(xhr.js:87)

这是在我的客户端使用的代码尝试从我的组件之一login:

//button

 <div> <button className="btn btn-danger" onClick={props.googleAuth}> Login With Google </button> </div> 

// STATEFUL COMPONENT方法

 googleAuth() { axios.get("http:localhost:3001/api/auth/google/login").then(res => { console.log("GOOGLE OAUTH 2 RES", res); }); } 

//控制器

 passport.use( new GoogleStrategy( { clientID: process.env.GOOGLE_CLIENT_ID, clientSecret: process.env.GOOGLE_CLIENT_SECRET, callbackURL: "/api/auth/google/callback", accessType: "offline" }, (accessToken, refreshToken, profile, done) => { const info = { googleUsername: profile.displayName, googleAccessToken: accessToken, googleRefreshToken: refreshToken, googleEmail: profile.emails[0].value }; User.findOrCreate({ where: { googleId: profile.id }, defaults: info }) .spread(user => { if (user) return done(null, user.toAuthJSON); // this is method that returns a signed JWT off user DB instance. return done(null, false); }) .catch(done); } ) ); // GOOGLE LOGIN router.get( "/login", passport.authenticate("google", { scope: [ "https://mail.google.com/", "https://www.google.com/m8/feeds/", "email", "profile" ] }) ); // GOOGLE CALLBACK router.get( "/callback", passport.authenticate("google", { session: false, }), (req, res) => { res.json(req.user.token) } ); 

我已经尝试和解决的步骤:

  • 我在浏览器上禁用了CORS
  • 我试图在我的路线/ api服务器端上的cors npm模块似乎没有任何工作。
  • 还有很多其他的修补和绝望

  • 基于这个错误,谷歌阻止我从我的服务器发出下游请求,并抛出错误(我认为)…

我的目标是:

  • 我希望Google返回一个用户对象,然后将其存储在我的数据库中(已经为此编码的逻辑)
  • 而不是服务器res.redirect()我想要res.json()一个签名的JWT(我已经正确地连线了)。
  • 我不想在我的服务器上使用基于会话的身份validation,并保持干净和无状态的东西。

这甚至可能吗?还应该指出,我有一个开发环境设置:

使用Concurrently启动服务器(同时启动客户机和nodemon服务器 – client @ localhost:3000向server @ localhost:3001发出代理请求) – 不确定这是否会导致任何问题?

任何帮助将不胜感激!