So I'm currently developing a MERN stack app and using google oauth for signup/signin. However, when I am calling a post call to mongodb to check the account to sign in, it doesn't show in the network calls at all and the console just shows the "Cross-Origin-Opener-Policy policy would block the window.closed call." error. I'm not sure if this is the primary reason or not, but attached below is my code.
import React, {useState, useEffect} from 'react';
import styles from './Account.module.css';
import axios from 'axios';
import {useGoogleLogin } from '@react-oauth/google';
import google from '../../icons/google.png';
function Login(){
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState('');
const {REACT_APP_BACKEND_HOST} = process.env;
// google authentication variables
const [ user, setUser ] = useState('');
const [ profile, setProfile ] = useState('');
const login = useGoogleLogin({
onSuccess: (codeResponse) => setUser(codeResponse),
onError: (error) => console.log('Login Failed:', error)
});
useEffect(
() => {
if (user) {
axios
.get(`https://www.googleapis.com/oauth2/v1/userinfo?access_token=${user.access_token}`, {
headers: {
Authorization: `Bearer ${user.access_token}`,
Accept: 'application/json',
Cross : 'same-origin-allow-popups'
}
})
.then((res) => {
setProfile(res.data);
console.log('hello set profile') ;
console.log(res.data) ;
})
.catch((err) => {console.log(err);
if (error.response &&
error.response.status >= 400 &&
error.response.status <= 500){
setError(error.response.data.message);
console.log('Signin failed.')
}
});
}
},
[ user ]
);
useEffect(()=>{
if(profile){
submitGoogle()
// axios.post(`${REACT_APP_BACKEND_HOST}api/users`,
// {
// email: profile.email,
// password: 'Test123!',
// firstName: profile.given_name,
// lastName: profile.family_name,
// num_generations: 2,
// num_referrals: 0,
// last_used: new Date().toString(),
// login_type: 'google',
// }).then((res)=>{
// console.log(res.message);
// localStorage.setItem("user", profile.email);
// localStorage.setItem("user_id", profile.id);
// window.location = '/';
// }).catch((error)=> {
// if (error.response &&
// error.response.status >= 400 &&
// error.response.status <= 500){
// setError(error.response.data.message);
// console.log('Signin failed.');
// }
// })
}
},[profile]);
const submitGoogle = async () => {
try{
console.log('submit google');
console.log(profile.given_name);
console.log(profile.email)
const date = new Date().toString();
console.log(date);
const {data:res} = await axios.post(`${REACT_APP_BACKEND_HOST}api/users`,
{
email: profile.email,
password: 'Test123!',
firstName: profile.given_name,
lastName: profile.family_name,
num_generations: 2,
num_referrals: 0,
last_used: date,
login_type: 'google',
});
console.log(res.message);
localStorage.setItem("user", profile.email);
localStorage.setItem("user_id", profile.id);
window.location = '/';
} catch(error){
if (error.response &&
error.response.status >= 400 &&
error.response.status <= 500){
setError(error.response.data.message);
console.log('Signin failed.');
}
}
}
const handleSubmit = async (e) => {
e.preventDefault();
const data = {
email: email,
password: password,
}
try{
const url = `${REACT_APP_BACKEND_HOST}api/auth`;
const {data:res} = await axios.post(url, data);
console.log(res.message);
localStorage.setItem("user", res.user.email);
localStorage.setItem("user_id", res.user._id);
window.location = '/';
} catch(error){
console.log('wrong here')
if (error.response &&
error.response.status >= 400 &&
error.response.status <= 500){
setError(error.response.data.message);
}
}
console.log(email, password);
}
const goToSignup = () => {
window.location = '/Signup'
}
return (
<div className= {styles.box}>
<form className={styles.center} onSubmit = {handleSubmit} >
<h2 style = {{margin: '30px'}}>Welcome back</h2>
<input
type='text'
onChange = {(e) => setEmail(e.target.value)}
placeholder='email' /> <br/>
<input
type='password'
onChange = {(e) => setPassword(e.target.value)}
placeholder='password'/>
<br/>
{error && <div className={styles.error_msg}>{error}</div>}
<button
type='submit'>
Log In
</button>
</form>
<button onClick={() => login()}
className={styles.googlebtn}
>
<h4>
<img src={google}
style={{width:'18px', marginRight:'10px'}}/>
Sign in with Google
</h4>
</button>
{error && <div>
<h3>{error}</h3>
</div>}
<h3 className={styles.account}
onClick = {goToSignup}
>Don't have an account? Sign up here.</h3>
</div>
)
};
export default Login;
It's specifically in the post request of the function "submitGoogle" where that post request isn't being shown. I have also double checked the backend call with thunderclient with the same json body and it works. I also logged the profile variable to see if the values were valid and they are. It's weird because there is no error being logged in the console from the request being called or anything. Any idea why that is?