I get an error, when I am using one method onLogin with the fetch inside the other onRegister.
I don't fully understand where the mistake.
Separately, the methods are working fine.
Stack:
Create React App
React router v6
Access to fetch at 'https://auth.blablabla/signin' from origin
'http://localhost:3000' has been blocked by CORS policy: No
'Access-Control-Allow-Origin' header is present on the requested
resource. If an opaque response serves your needs, set the request's
mode to 'no-cors' to fetch the resource with CORS disabled.
function onRegister({ email, password }) {
auth.register(email, password)
.then((res) => {
try {
// here when when using the method I get the error.
onLogin(email, password);
} catch (error) {
console.log(error);
}
}).catch(err => {
console.log('Error to registartion: ', err);
});
}
function onLogin({ email, password }) {
auth.login(email, password)
.then(res => {
if (res.token) {
setIsLoggedIn(true);
localStorage.setItem('jwt', res.token);
setEmail(email);
navigate('/');
}
}).catch(err => {
console.log('Error log: ', err);
}
);
}
But this is methods for auth: register and login
export const register = (email, password) => {
return fetch(`${BASE_URL}/signup`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
'Accept': 'application/json'
},
body: JSON.stringify({
password,
email
})
})
.then((res) => {
try {
if (res.status === 201) {
return res.json();
}
if (res === 400) {
return Promise.reject('in one of the fields of the error');
}
} catch (error) {
console.log(error);
}
})
.then((res) => {
return res;
})
.catch((error) => console.log(error))
}
export const login = (email, password) => {
return fetch(`${BASE_URL}/signin`, {
method: 'POST',
headers: {
"Content-Type": "application/json",
'Accept': 'application/json'
},
body: JSON.stringify({
password,
email
})
})
.then((res) => {
try {
if (res.ok) {
return res.json();
}
if (res.status === 401) {
return Promise.reject('user for this email not found');
}
if (res.status === 400) {
return Promise.reject('fill in all the fields');
}
} catch (error) {
console.log(error);
}
})
.then((data) => {
localStorage.setItem('jwt', data.token)
localStorage.setItem('email', email);
return data;
})
.catch((err) => console.log(err))
}