You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React与JS API中Promise resolve返回undefined问题求助

问题排查与解决方案

1. 前端postAuth未返回数据导致undefined

你的postAuth函数执行完axios请求后没有返回任何值,这直接导致await postAuth()拿到的结果是undefined。修改如下:

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:''
    })
    // 返回后端实际返回的数据,axios会把响应内容放在response.data中
    return response.data;
};

2. 拼写错误:lenght → length

handleSubmit里的判断条件存在拼写错误,response.lenght应该改为response.length,错误的拼写会导致判断逻辑永远不成立:

if (response.length != 0){ // 修正拼写错误
    navigAcc('/Accueil');
}

3. 后端Promise逻辑的确认

你的userAuth函数中Promise的写法本身没有问题,但需要确认数据库查询返回的utilisateur结构:多数SQL库执行SELECT语句后返回的是结果数组,如果没有匹配的用户,数组长度为0。可以在后端的then回调中打印日志确认:

.then((response) => {
    console.log("数据库返回结果:", response); // 查看输出是否为预期的数组结构
    res.send(response);
})

4. 紧急修复:SQL注入风险

当前代码直接拼接用户输入到SQL语句中,存在严重的SQL注入漏洞,必须改成参数化查询(以MySQL为例):

userAuth = (identifiant, mdp) => {
    return new Promise((resolve, reject) => {
        // 使用?作为占位符,参数通过数组传入
        config.query(
            "SELECT identifiant, mdp FROM utilisateur WHERE identifiant = ? and mdp = ?",
            [identifiant, mdp],
            (error, utilisateur) => {
                if (error) {
                    return reject(error);
                }
                return resolve(utilisateur);
            }
        );
    });
};

内容的提问来源于stack exchange,提问作者Guigasp

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.26 04:02:29