【问题标题】:Why I can not get correct response from api?为什么我不能从 api 得到正确的响应?
【发布时间】:2020-08-31 10:39:06
【问题描述】:

我无法从我的 api 获得好的答案,例如我尝试从 api 读取“true”或“false”以授予 user 的授权,但我得到的只是未定义的数据。 从发送数据到验证用户,这两种方法都可以完美运行。

我在服务器中有这个 api 方法:


router.get("/sickers/user/login/:mail/:pass", (req, res) => {
    //var values = JSON.parse(req.body);
    var pass = req.params.pass;
    var email = req.params.mail;
    //console.log(values);
    if (pass !== null || pass !== "") {
        try {
            con.connect();
            con.query("SELECT Password FROM `sickers` WHERE Email='" + email + "'", function(err, rows, field) {
                if (err) {
                    console.log(err);
                    res.send("an error detected try later");
                } else {
                    try {

                        if (pass == rows[0].Password) {

                            res.json({ "result": "true" })
                        } else {
                            res.json({ "result": "false" })
                        }
                    } catch {

                        res.json({ "result": "false" })
                    }

                }
            });
        } catch (e) {
            res.send("no data found");
            console.log("obj not found");
        }
    }
 con.end();
});

这个调用 api 在我的反应应用程序中:

submithandler(e) {
   e.preventDefault();
        const url = 'http://localhost:8000/api/sickers/user/login/'+this.state.email+'/'+this.state.password+'';
        const res =  fetch(url);
        const data = res;
        this.setState({result:data});
       alert(this.state.result);

    }

谢谢。

【问题讨论】:

  • fetchsetState 都是异步的。您需要等待fetch 调用,或将其余代码添加到.then 回调中,并从setState 回调中发出警报,以便事情按照您期望的顺序执行。

标签: node.js reactjs api express


【解决方案1】:

考虑到您正在使用的函数的异步特性。它可能看起来像这样:

const url = 'http://localhost:8000/api/sickers/user/login/'+this.state.email+'/'+this.state.password+'';
// Use .then to call a function AFTER the fetch has completed
fetch(url).then(result => result.json()).then((response) => {
  // Use the setState callback to check updated values AFTER they have been updated
  this.setState({result: response}, () => {
    alert(this.state.result);
  });
});

Docs on fetch

Docs on setState

【讨论】:

  • 感谢您的回复,我已经尝试过了,我仍然得到“未定义”的分析器,我尝试了 this.state.result.result 因为我有从 api 发送的 json,例如:{“result”:“ true" } ,所以我需要在 json 中获取结果的值,每件事都显示“未定义”。
猜你喜欢
  • 1970-01-01
  • 2020-06-24
  • 1970-01-01
  • 2023-04-03
  • 2021-01-06
  • 1970-01-01
  • 2020-09-08
  • 2021-03-18
  • 2016-11-04
相关资源
最近更新 更多