【问题标题】:Inserting into mysql using express and nodejs使用 express 和 nodejs 插入 mysql
【发布时间】:2020-08-31 16:26:56
【问题描述】:

我想知道使用 express 和 node js 从脚本中提取的查询填充 MySQL 数据库的最佳途径是什么。

我在 3000 端口上运行的脚本如下所示:

curl localhost:3000/register?name=bob\&width=13.970000\&time=0
curl localhost:3000/wheels?left=0.000000\&right=0.000000\&time=0 --cookie "USER=bob"
curl localhost:3000/echo?dist=9.220000\&time=10 --cookie "USER=bob"
curl localhost:3000/line?l1=1\&l2=1\&l3=1\&time=20 --cookie "USER=bob"
curl localhost:3000/other?ir=0\&time=30 --cookie "USER=bob"
curl localhost:3000/wheels?left=3.000000\&right=3.000000\&time=100 --cookie "USER=bob"
curl localhost:3000/echo?dist=9.220000\&time=110 --cookie "USER=bob"
curl localhost:3000/line?l1=1\&l2=1\&l3=1\&time=120 --cookie "USER=bob"
curl localhost:3000/other?ir=0\&time=130 --cookie "USER=bob"
curl localhost:3000/wheels?left=3.000000\&right=3.000000\&time=200 --cookie "USER=bob"
curl localhost:3000/echo?dist=9.220000\&time=210 --cookie "USER=bob"
curl localhost:3000/line?l1=1\&l2=1\&l3=1\&time=220 --cookie "USER=bob"

我的 app.js 文件如下所示:

const express = require('express');
const cookieParser = require('cookie-parser');
const mysql = require('mysql');

let app = express()

app.use(cookieParser());

var pool = mysql.createPool( {
        host: 'localhost',
        user: 'root',
        password: 'root',
        database: 'cars',
        connectionLimit: 10,
        multipleStatements : true
});

app.get('/register', function(req, res) {
                mysql.pool.query("INSERT INTO todo (`name`) VALUES (?)", [name], function( err, results ) {
                        if (err)
                                throw err

                response.send(results);
                })
        });




app.listen(3000, function(req, res) {
        console.log('Express JS ready for port 3000');
});

我的数据库在 phpMyAdmin 中设置,如下所示: My database using phpMyAdmin

当我在端口 3000 上运行脚本时,我不断收到的错误是:

TypeError: Cannot read property 'query' of undefined

最终我想使用 /wheels、/line、/echo 等来填充 MySQL 数据库。但我越是搞砸它,我得到的类似错误就越多。任何人都知道我可能会出错的地方,或者可以指出我在哪里可以学习如何正确地做这样的事情?谢谢

【问题讨论】:

  • 你不需要mysql.pool,只需要pool,因为它被声明为一个变量
  • 谢谢!现在我得到的错误是:ReferenceError: name is not defined
  • 因为 name 是一个查询参数并且尚未定义,所以您需要 req.query.name,引用错误通常通过找出缺少和/或不正确的内容来解决。调试很有用,是所有程序员都应该具备的技能,一旦学会,ReferenceErrors 之类的东西就不会减慢你的速度。
  • 调试非常好用,是我写C++的时候熟悉的技能。。就是不懂node js,也不懂表达。我只完成了几个 youtube 教程,但我仍然很迷茫。我的校园已经关闭,所以我现在除了在互联网上没有其他地方可以寻求帮助。我越来越多地使用应用程序,现在当我运行脚本时,我得到“curl:(52)来自服务器的空回复”当我所做的只是将查询参数更改为:pool.query(“INSERT INTO cars(@ 987654325@) VALUES (?)", [req.query.name], function(err, results) 我也把 mysql db 改成不严格了
  • 如果你擅长调试 C++,它应该很容易应用于 Node.js 和 Express,语言应该无关紧要。关于空响应,仔细检查结果是使用console.log定义的,我认为它不是,所以它给出了一个空响应。

标签: mysql node.js express


【解决方案1】:
// file: server.js
const express = require('express');
const db = require('./db');
const app = express();

// you may wish to reconsider the use of .get at some stage
// what happens when you want to retrieve an item?
app.get('/models', (req, res) => {
  // learn about validation when you're comfortable with basics
  // this is especially important for public facing apps
  if (!req.query.manufacturer || !req.query.type || !req.query.cost) {
    return res.status(400).send('wrong input!'); // super helpful error messages
  }

  const public = req.query.public || true; // set defaults
  const { manufacturer, type, cost } = req.query;

  // when you're more comfortable, learn about abstractions + Service pattern
  // removing DB queries from route handlers, pushing the responsibility to a Service.
  db.query(
    'INSERT INTO car_models(manufacturer,type,cost,public) VALUES (?,?,?,?)',
    // learn about SQL injection, I **hope** the mysql package author considered it.
    [manufacturer, type, cost, public],
    (err, results) => {
      if (err) {
        console.error(err);
        return res.status(500).send('oh no');
      }

      return res.status(201).send(`Created ID: ${results.insertId}`);
    }
  );
});

app.listen(3000, () =>
  console.log('service started... accepting requests on http://localhost:3000')
);
/**
 *  File: db.js
 *  Responsibility: connect to MySQL
 *  Note: you could use an ORM here (**could** not always **should**)
 */
const mysql = require('mysql');
const connection = mysql.createConnection({
  host: 'localhost',
  user: 'develop',
  password: 'development',
  database: 'cars',
  port: 3306,
});

connection.connect((err) => {
  if (err) {
    console.error(`MySQL: Failed to connect to MySQL: ${err.message}`, err);
    return;
  }

  console.log('MySQL: Successfully connected to MySQL');

  connection.query(`CREATE TABLE IF NOT EXISTS car_models (
    id INT PRIMARY KEY AUTO_INCREMENT,
    manufacturer VARCHAR(30),
    type VARCHAR(10),
    cost BIGINT,
    public BOOLEAN
  );`);
});

module.exports = connection;

我想到了另一个例子,为了简单起见,我保留了与您相似的样式,希望这有助于您理解它。

如果您有任何不确定的地方,我建议您研究一下。我不建议预先研究所有内容。我倾向于在需要时或在有机会时研究事物。 (以通勤为例)

尽管找到某种形式的平衡很重要,但您将通过实践而不是研究学到更多。如果没有,您最终将学习如何用一种语言做某事,并且仅限于该语言和语言功能的一小部分。 (也许,也许不是)。

添加新车型非常简单: curl http://localhost:3000/models?manufacturer=bmw&type=m3&cost=10000

或者,尝试在您使用的任何浏览器中打开http://localhost:3000/models?manufacturer=bmw&type=m3&cost=10000(当它运行时),看看会发生什么。您可能会发现浏览器(或 Postman)会更易于使用。或者你可能不会。

有一个非常重要的部分:没有会话,没有 cookie,不知道最后一个请求,什么都没有。这是无国籍的。对于简单的操作,不需要引入这种机制,因为它根本不需要。

我建议学习如何构建 Express.js(它非常灵活),您可以遵循一些模式和最佳实践,但可能要等到您先熟悉该语言,否则它可能是一只兔子洞。

最后一点,了解无状态系统和有状态系统的区别。不要花费数小时,可能需要 5 分钟,以便您了解每个背后的关键概念。然后,您可以利用这些知识自行决定无状态还是有状态。

我希望我早点学到一些东西:要解决问题,您需要了解您要解决的问题。听起来很基本,但我偶尔还是会出错。

祝你好运,万事如意!

【讨论】:

  • 谢谢你!我试图重新设计它以适应我正在做的事情,但我真的无法做到。它的工作方式有点像我的第一个示例,但它并没有在填写表格时创建新数据库。我将很快在这里发布另一个项目更新,其中包含我所拥有的。现在,我只需要弄清楚如何让 node js/express 填满后创建一个新的数据表。
  • 这是我目前所做的更新,希望它们能让您更好地了解我想要实现的目标:stackoverflow.com/questions/61842957/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-07-21
  • 2014-05-24
  • 2018-10-31
  • 1970-01-01
  • 2011-08-18
  • 1970-01-01
  • 2014-11-15
相关资源
最近更新 更多