我正在使用npm mysql package,使用dbHandler.js
为我的mysql数据库创建一个连接池:
var mysql = require("mysql");
var pool = mysql.createPool({
connectionLimit : 10,
host: "path.to.host",
user: "username",
password: "password",
database: "dbname",
debug: false
});
exports.pool = pool;
然后我在routesHandler.js
内调用它来处理我的SQL请求:
var mysql = require("mysql");
var pool = require("./dbHandler");
exports.login = function(req, res) {
var email = req.body.email;
pool.query('SELECT * FROM users WHERE users.email = ?', [email], function(
error,
results,
fields
) {
if (error) {
res.send({
code: 400,
failed: "Error ocurred"
});
} else {
if (results.length > 0) {
//Mail authorized
res.send({
code: 200,
success: "Sucessfull login"
});
} else {
//Mail unauthorized
res.send({
code: 403,
failed: "Unauthorized mail"
});
}
}
});
};
我不确定这是最好的方法,但我似乎找不到合适的例子......:/
我很乐意:)接受关于处理整体的方式的任何建议或链接:
但是我收到了这个基本的错误信息,但我无法弄清楚如何摆脱它:
TypeError:pool.query不是函数
欢迎任何指示!
答案 0 :(得分:1)
我认为你必须在这个函数之前使用opencl
:
async/await
但即时通讯说“我认为现在会有效”
答案 1 :(得分:1)
你做exports.pool所以你必须调用池的专有权
如果您在dbHandler中使用module.exports=pool
,那么如果不是仅使用我的答案,您的代码将按原样运行
var pool = require("./dbHandler").pool;
exports.login = function(req, res) {
var email = req.body.email;
pool.query('SELECT * FROM users WHERE users.email = ?', [email], function(
error,
results,
fields
) {
if (error) {
res.send({
code: 400,
failed: "Error ocurred"
});
} else {
if (results.length > 0) {
//Mail authorized
res.send({
code: 200,
success: "Sucessfull login"
});
} else {
//Mail unauthorized
res.send({
code: 403,
failed: "Unauthorized mail"
});
}
}
});
};
答案 2 :(得分:0)
我遇到了类似的问题,我尝试了大多数可用的解决方案,但是它们都没有起作用,最后,我找到了解决问题的答案。
dbHandler.js
文件:
var Pool = require('pg').Pool;
var pool = new Pool({
user: 'postgres',
host: 'localhost',
database: 'database_name',
password: '#############',
port: 5432,
});
module.exports = {pool};
anotherfile.js
:
let {pool: pool} = require('dbHandler');
// by this calling method I was able to use pool