I'm new to React as well as js and I kinda struggle a bit to understand how Promise and resolve work.
I'm trying to do an api to log onto an app with an internal database in SQL. The queries are fine and return what they need to return, but weirdly enough, the resolve of the json data doesn't end up working and it returns as an undefined.
Here's the current relevant code from the api:
userAuth = (identifiant, mdp) => {
return new Promise((resolve, reject) => {
config.query(
"SELECT identifiant, mdp FROM utilisateur WHERE identifiant = '"+identifiant+"' and mdp = '"+mdp+"'",
(error, utilisateur) => {
if (error) {
return reject(error);
}
//une petite manipulation de donnée pour éviter des soucis de format par la suite.
return resolve(utilisateur);
}
);
});
};
app.post("/auth", (req, res) => {
console.log("connection");
const data = {
identifiant: req.body.Identifiant,
mdp: req.body.Password,
};
console.log(data);
userAuth(data.identifiant, data.mdp)
.then((response) => {
console.log(response);
res.send(response);
})
.catch((error) => {
console.log(error);
res.status(500).send("Erreur serveur");
});
});
And here's the relevant code from my app:
const handleSubmit = async (event) => {
event.preventDefault();
const id = formAuth.Identifiant;
const password = formAuth.Password;
if(!password.match(re)){alert("Format de mot de passe incorrect")}
else {
const response = await postAuth();
console.log(response);
if (response.lenght != 0){
navigAcc('/Accueil');
}
else{
alert("Identifiant ou mot de passe incorrect")
}
}
}
const postAuth = async () => {
const body = {
Identifiant: formAuth.Identifiant,
Password: formAuth.Password
};
const config = {
headers: {
'Content-Type': 'application/json'
}
};
const response = (await axios.post(api+"auth", body, config));
setFormAuth({
Identifiant:'',
Password:''
})
};
I have found another similar question on the site (why router is undefined in react js?) but I don't see any actual meaningful difference between what I'm doing and the answer submitted so I feel really lost.
I tried to parse the api's response in json even if it already was to see if it was a type error, I tried treating the response from the app like an array, I tried treating it like a boolean based on if it was empty or not to see if I could just not care about what is specifically inside since it would only be filled anyway if the authentification works. I don't really see the problem but I know it's located specifically on the Promise from userAuth since it'sthe only thing that seem to create or reformulate errors when I touch it.