【发布时间】: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定义的,我认为它不是,所以它给出了一个空响应。