nodeJS中的查询和表达问题



我正在使用express为nodeJS服务器开发一个网页。我正在使用注册页面,并试图验证用户插入的数据,但当我进行查询时,我收到了一个错误。

auth.js

const express = require('express');
const router = express.Router();
const { bd } = require('../database');
const help_functions = require('../lib/common');
router.post('/signup', async (req,res) => {
const fullname = req.body['fullname'];
const email = req.body['email'];
const username = req.body['username'];
const password = req.body['password'];
const password_repeat = req.body['password_repeat'];
var validation_msg = help_functions.validateSignUp(fullname, email, username, password, password_repeat);
validation_msg = await help_functions.checkRepeatedUserEmail(email);
});

database.js

const mysql = require('mysql');
const { promisify } = require('util');
const database =  { // Database credentials }
const bd = mysql.createPool(database);
bd.getConnection((err,connection) => {
if (err) {
if (err.code === 'PROTOCOL_CONNECTION_LOST') {
console.error('Database connection failed !');
}
if (err.code === 'ER_CON_COUNT_ERROR') {
console.error('Database has too many connections !');
}
if (err.code === 'ECONNREFUSED') {
console.error('Database connection was refused !');
}
}
if (connection) {
connection.release();
console.log('Database is connected !');
return;
}
});
bd.query = promisify(bd.query);
module.exports = bd;

common.js

const { bd } = require('../database');
const helper_functions = {}
helper_functions.validateSignUp = (fullname, email, username, password, password_repeat) => {
if (fullname === '' || email === '' || username === '' || password === '' || password_repeat === '') {
return 'All the fields had to be completed!';
}
if (!(password.length >= 8 && (/d/g.test(password) && (/[A-Z]/.test(password)))) ) {
return 'The password needs to contain at least one capital letter, a number and 8 digits!';
}
if(password != password_repeat) {
return 'Both passwords had to be the same!';
}
return 'Validated!';
}
helper_functions.checkRepeatedUserEmail = async (email) => {
const user = await bd.query('SELECT * FROM users WHERE email = ?', [email]);
if (user.length) {
return 'This email is used, please change it!';
} else {
return 'Validated!';
}
}
module.exports = helper_functions;

错误显示下一个文本:

(节点:14616(未处理的PromiseRejectionWarning:TypeError:无法读取未定义的属性"query"位于Object.helper_functions.checkRepeatedUserEmail(proyect_path/src/lib/common.js:19:27(…………

(节点:14616(未处理的PromiseRejection警告:未处理的promise拒绝此错误源于在异步内部引发函数没有catch块,或者通过拒绝未使用.catch((处理。在未处理时终止节点进程承诺拒绝,使用CLI标志--unhandled-rejections=strict(参见https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode)。(拒绝id:2((节点:14616([DEP0018]弃用警告:未处理不赞成拒绝承诺。未来,拒绝承诺未处理的将使用非零退出代码。

有人知道发生了什么吗??感谢阅读!

您将数据库公开为database.js:中的默认导出

module.exports = bd;

但您导入它时,就好像它是用名称db:导出的一样

const { bd } = require('../database');

database.js中的导出更改为:

module.exports = {
bd: bd
};

或者在common.js文件中导入为:

const bd = require('../database');

common.js文件中没有定义db的错误可能是您做了错误的请求('../database'(;require语句中有一个错误。使用调试器在这一点上停止,看看您是否在那里获得数据库。

最新更新