【问题标题】:mysql function does not work in react after several excutionmysql 函数在多次执行后在反应中不起作用
【发布时间】:2021-06-10 03:08:52
【问题描述】:

这里是 node.js 代码

var _num;
app.post("/api/get", (req, res) => {
    _num = req.body.passNum;
    console.log(_num + "insert");
    callDb();
});



var callDb = () => {
    app.get
    ("/api/get", (req, res) => {
        var sqlSelect = "SELECT * FROM day" + _num;
        console.log(_num + "outcome");
        db.query(sqlSelect, (err, result) => {
            res.send(result);

        });
    });
};
  1. 这段代码是什么? :此代码通过单击 url(从第 1 天到第 3 天)从前端(反应)获取一个数字,并将其传递到后端内部的 var _num。 并且函数 callDb 获取 var _num,并添加到 mysql 查询中,因此总之 callDb 从 mysql 调用不同的表(从第 1 天到第 3 天)。

  2. 什么问题? : 前几次正常,点击几次就不能正常了。正如您在我的代码中看到的,为了检查它是否正常工作,我添加了 console.log(插入和结果)。作为app.post中的callDb,_num从react中获取数字后,必须启动callDb。

所以顺序是,点击day1 url->_num得到值“1”,console.log insert出来(1 insert)->callDb SELECT day1,console.log结果出来(1个结果)。

重复点击后返回主页面,日志为

1插入 1个结果

2插入 2结果

3插入 3结果

1插入 1个结果

2插入 2结果

3插入

所以从六次开始,问题就来了。只出现插入,点击后没有日志变化。这意味着 SELECT 没有工作。刷新页面后,控制台日志结果会给出正确的结果。所以每6click,用户需要刷新。

我真的很困惑,因为它工作了好几次,并且在某些时候它会刹车。有什么问题,我该如何解决?

【问题讨论】:

  • 您是否将原始 SQL 从客户端前端传递到您的 MySQL 服务器?
  • 来自 node.js。从前端仅通过 axios 获取 _num 并且当 node.js 选择正确的表时,它会在前端显示该表。

标签: mysql reactjs


【解决方案1】:
    app.post("/api/get", (req, res) => {
    if(req.body.passNum){//first check if the required parameter is provided
        _num = req.body.passNum; //get the parameter. You need to use 'escape string' to escape other dangerous characters which may lead to sql imjection.
        
        db.query("SELECT * FROM day" + _num, (err, result) => {
            if (err) {
                console.log(err);          
                res.end("An error occcured while reading from the database");
            } else {
                res.send(result);
            }
        });
    }else{
        res.end("required fields are not provided");
    }    
});

【讨论】:

  • 我已将我的代码更改为您的代码,但在 chrome 上显示 GET localhost:3001/api/get 404 (Not Found)。我很确定我的原始代码在获取参数之前一直有效。并且node.js终端没有登录。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-05-01
  • 2020-06-03
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多