'ReactJS call to back-end route to login user with Google/Facebook

I have a NodeJS Express server running on localhost:5000 Also my ReactJS server is running on port localhost:3000

I try to implement login with oAuth2.0 Google but having troubles making calls to back-end route from my React application.

I have Google login strategy on my back-end tested and it is working. Generates me a token and returns it.

BACKEND ROUTES (tested and it works, generates and return me a token after selecting google account)

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}`
    });
  });
};

I mentioned before that Im having troubles in ReactJS. What is the proper way to make a call from my front-end to backend to get that JWT token?

I have proxy in my package.json

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

From my component I try to do regular axios call my backend to get that window opened to select google user... I kind a lost in this part how it should work. My code:

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;

Error I get:

Access to XMLHttpRequest at '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' (redirected from 'http://localhost:3000/api/auth/google') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.



Solution 1:[1]

Try to add this

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

You have to enable cors on your express app : enable cors on nodejs

Solution 2:[2]

1.First install cors package And require('cors').

2.Then copy the following code

    app.use(
      cors({
         origin: "http://localhost:3000", 
         // allow to server to accept request from different origin
         methods: "GET,HEAD,PUT,PATCH,POST,DELETE",
         credentials: true // allow session cookie from browser to pass through
           })
        );

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 L.Lecherbonnier
Solution 2