ReactJS呼叫使用Google / Facebook登录用户的后端路由

问题描述 投票:0回答:1

我有一个在localhost上运行的NodeJS Express服务器:5000我的ReactJS服务器也在端口localhost:3000上运行

我尝试使用oAuth2.0 Google实现登录,但是从我的React应用程序调用后端路由时遇到了麻烦。

我的后端测试中有谷歌登录策略,它正在运行。生成一个令牌并返回它。

BACKEND ROUTES(经过测试并运行,生成并在选择Google帐户后返回一个令牌)

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

router.get(
  '/api/auth//google/redirect',
  passport.authenticate('google', { session: false }),
  (req, res) => {
    signToken(res, req.user);
  }
);

// Sign JSON Web Token, expires in 60 minutes
const signToken = (res, user) => {
  const payload = {
    id: user.id,
    name: user.name,
    email: user.email,
    role: user.status.role
  };

  jwt.sign(payload, keys.secretOrKey, { expiresIn: 3600 }, (err, token) => {
    res.json({
      success: true,
      token: `Bearer ${token}`
    });
  });
};

我之前提到我在ReactJS中遇到了麻烦。从我的前端到后端进行调用以获取JWT令牌的正确方法是什么?

我的package.json中有代理

 "proxy": "http://localhost:5000"

从我的组件我尝试做常规axios呼叫我的后端打开窗口选择谷歌用户...我在这部分失去了它应该如何工作。我的代码:

import React, { Component } from 'react';
import axios from 'axios';

class testLogin extends Component {
  onGoogleClick = () => {
    axios
      .get('/api/auth/google')
      .then(res => console.log(res.data))
      .catch(err => console.log(err));
  };
  render() {
    return (
      <div>
        <button onClick={this.onGoogleClick}>Login With Google Account</button>
      </div>
    );
  }
}

export default testLogin;

我得到的错误:

从'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A5000%2Fapi%2Fauth%2Fgoogle%2Fredirect&scope=profile%20email&client_id=510739647280-cggqldrpluvg35do2lv83ud3118pgal5.apps.googleusercontent.com'访问'http://localhost:3000/api/auth/google'(从'http://localhost:3000'重定向)的XMLHttpRequest已被CORS策略阻止:请求的资源上没有'Access-Control-Allow-Origin'标头。

node.js reactjs express oauth-2.0
1个回答
1
投票

尝试添加此功能

app.use((req, res, next) => {
      res.setHeader('Access-Control-Allow-Origin', '*')
      next()
})

你必须在你的快递应用程序上启用cors:enable cors on nodejs

© www.soinside.com 2019 - 2024. All rights reserved.