无法在Mysql&Express Node JS中转义限制值

问题描述

我正在使用Node.js(+ Express JS)和MysqL开发API。我无法转义或将自定义限制值添加查询中。这是我的路线;

app.post('/api/v1/fetch/limitedArticles/:limit',(req,res,) => {

    const limitValue = req.params.limit;

    let query = "SELECT article_id,article_name,article_image,article_url FROM ?? ORDER BY article_id DESC LIMIT ?";

    MysqLDB.query(query,['app_articles',limitValue],function (MysqLError,MysqLRes) {
        if(MysqLError){
            return res.status(500).send({message: "error_server_db"});
        }else if(MysqLRes.length<1){
            return res.status(404).send({message: "warning_empty_list"});
        }else{
            //All good
            return res.status(200).send(MysqLRes);
        }
        throw MysqLError;

    })
});

我要求为

{{api_base_url}}/api/v1/fetch/limitedArticles/2

我得到这个错误

{
"message": {
    "code": "ER_PARSE_ERROR","errno": 1064,"sqlMessage": "You have an error in your sql Syntax; check the manual that corresponds to your MariaDB server version for the right Syntax to use near ''2'' at line 1","sqlState": "42000","index": 0,"sql": "SELECT article_id,article_url FROM `app_articles` ORDER BY article_id DESC LIMIT '2'"
}

}

如果我删除参数值并输入“ 2”作为我的极限值(例如LIMIT 2),它将起作用。但这不像我展示的那样。

解决方法

limitValue是一个字符串-您应将其转换为数字,以便可以在limit子句中使用:

const limitValue = Number(req.params.limit);