我是 React 和 js 的新手,我有点难以理解 Promise 和 resolve 的工作原理。
我正在尝试使用 API 来登录具有 SQL 内部数据库的应用程序。查询很好并返回了它们需要返回的内容,但奇怪的是,json 数据的解析最终并没有工作,而是以未定义的形式返回。
以下是 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");
});
});
这是我的应用程序中的相关代码:
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:''
})
};
我在网站上发现了另一个类似的问题(为什么 router 在 React js 中未定义?),但我没有看到我正在做的事情和提交的答案之间有任何实际有意义的差异,所以我感到非常迷失。 p>
我尝试解析 json 中的 api 响应,即使它已经是一个类型错误,我尝试将应用程序的响应视为数组,我尝试将它视为基于是否为布尔值空或不空,看看我是否可以不关心里面具体是什么,因为只有在验证有效的情况下它才会被填充。 我并没有真正看到问题,但我知道它专门位于 userAuth 的 Promise 上,因为当我触摸它时,它似乎是唯一会创建或重新表述错误的东西。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
我忘记在 postAuth 后返回它。
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:'' }) return response; };