【问题标题】:I can't insert data to my database (mysql)我无法将数据插入我的数据库(mysql)
【发布时间】:2020-01-23 07:32:06
【问题描述】:

我现在正在学习 MySQL,但遇到了一些问题。我试图向我的数据库发出发布请求::

我的客户端代码:

async function sendValues() {
    const settings = {
        method: 'post',
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(product)
    }
    try {
        const fetchResponse = await fetch('http://localhost:9001/products', settings);
        const data = await fetchResponse.json();
        console.log(data) // what the user send
    } catch (err) {
        return err
    }
}

我的服务器端代码:

router.post('/', (req, res) => {
    const { c_id, p_name, p_price } = req.body
    const q =
        `
        INSERT INTO products (c_id,p_name,p_price)
        VALUES("${c_id}", "${p_name}" , "${p_price}")
        `;
    con.query(q, (err, result, fields) => {
        if (err) throw err;
        res.json(result)
    });
});

【问题讨论】:

  • 首先,确保您可以在客户端和服务器之间建立正确的连接。然后就可以执行查询了。

标签: javascript mysql node.js reactjs express


【解决方案1】:

有两种可能的错误:

1.检查客户端和服务器之间的连接。如上所述。

2.检查表名,属性的数据类型,你提供的属性名称。

【讨论】:

    【解决方案2】:

    其余端点是/,您正在调用products,如下更改您的后端代码。

    router.post('/products', (req, res) => {
        const { c_id, p_name, p_price } = req.body
        const q =
            `
            INSERT INTO products (c_id,p_name,p_price)
            VALUES("${c_id}", "${p_name}" , "${p_price}")
            `;
        con.query(q, (err, result, fields) => {
            if (err) throw err;
            res.json(result)
        });
    });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-03-02
      • 1970-01-01
      • 1970-01-01
      • 2019-01-07
      • 2017-11-08
      • 2012-08-05
      • 2016-03-29
      • 2019-10-06
      相关资源
      最近更新 更多