如何让我的 Node.js MySQL 连接作为承诺工作?
Posted
技术标签:
【中文标题】如何让我的 Node.js MySQL 连接作为承诺工作?【英文标题】:How can I make my Node.js MySQL connection as a promise work? 【发布时间】:2020-07-10 16:25:09 【问题描述】:刚开始接触node.js,js知识有点生疏。
我从回调开始,然后我发现了 Promise。这种语法更像是我的大脑工作,所以我用 Promise 重写了我的代码。 但现在我的 mysql 连接不起作用。它甚至无法到达(我认为...) 我已经在文件 userDB 中记录了“test”这个词,它起作用了。但随后在 mySql 文件中,console.log "test2" 不起作用。
谢谢大家! 克里斯
这是我的 server.js(节点启动的文件):
/* REQUIRE */
const oAuth2Server = require('node-oauth2-server');
const express = require('express');
const bodyParser = require('body-parser');
const oAuthModel = require('./endpoints/auth/authModel');
const util = require('util');
const dbCon = require('./subsystem/mySql')
/* CONST */
const port = 3000;
const debug = true;
const app = express();
/* INIT */
app.oauth = oAuth2Server(
model: oAuthModel,
grants: ['password'],
debug: debug
)
/* ROUTER */
app.use(bodyParser.json());
app.use(bodyParser.urlencoded( extended: true ));
app.use(app.oauth.errorHandler());
const authRoutes = require('./router/auth')(express.Router(), app, dbCon)
app.use('/auth', authRoutes);
app.all('*', (req, res) =>
res.status(404).send(message: "This service was not found");
);
/* Start Server */
app.listen(port, () =>
console.log(`listening on port $port`)
)
这是我的路由器文件 auth.js:
module.exports = (router, expressApp, dbCon) =>
const userDB = require('../endpoints/user/userDB')(dbCon)
const authMiddleware = require('../endpoints/auth/authMiddleware')
const userMiddleware = require('../endpoints/user/userMiddleware')(userDB)
router.post('/registerUser', userMiddleware.registerUser)
//router.post('/login', expressApp.oauth.grant(), authMiddleware.login)
router.post('/login', expressApp.oauth.grant())
return router
这是我的用户数据库文件:
let mySqlConnection;
module.exports = injectedMySqlConnection =>
mySqlConnection = injectedMySqlConnection
return
registerUserInDB: registerUserInDB,
getUserFromCrentials: getUserFromCrentials,
doesUserExist: doesUserExist,
getUserByUsername: getUserByUsername
const registerUserInDB = (username, password) =>
return new Promise((resolve,reject) =>
//execute the query to register the user
mySqlConnection.query(`INSERT INTO users (username, user_password) VALUES ('$username', SHA('$password'))`)
.then(data => resolve(true))
.catch(error => reject(error))
)
const getUserFromCrentials = (username, password) =>
return new Promise((resolve,reject) =>
//create query using the data in the req.body to register the user in the db
const getUserQuery = `SELECT * FROM users WHERE username = '$username' AND user_password = SHA('$password')`
console.log('getUserFromCrentials query is: ', getUserQuery);
//execute the query to get the user
mySqlConnection.query(getUserQuery)
.then(data => resolve(data))
.catch(error => reject(error))
)
const doesUserExist = username =>
return new Promise((resolve,reject) =>
console.log('test');
//execute the query to check if the user exists
mySqlConnection.query(`SELECT * FROM users WHERE username = '$username'`)
.then(data => resolve(data.results !== null ? data.results.length == 1 ? true : false : false))
.catch(error => reject(error))
)
const getUserByUsername = username =>
return new Promise((resolve,reject) =>
//execute the query to check if the user exists
mySqlConnection.query(`SELECT id, username FROM users WHERE username = '$username'`)
.then(data => resolve(data))
.catch(error => reject(error))
)
这是我的用户中间件(这是中间件吗?):
let userDb;
module.exports = injectedUserDb =>
userDb = injectedUserDb
return
registerUser: registerUser
function registerUser(req, res)
console.log(`authRoutesMethods: registerUser: req.body is:`, req.body);
//query db to see if the user exists already
userDb.doesUserExist(req.body.username)
.then(data =>
if(data)
sendResponse(res, "User already exists", 200)
return
else
//register the user in the db
userDb.registerUserInDB(req.body.username, req.body.password)
.then(data =>
userDb.getUserByUsername(req.body.username)
.then(data => sendResponse(res, data.results, ""))
.catch(error => sendResponse(res, "Failed to register user", error))
)
.catch(error => sendResponse(res, "Failed to register user", error))
)
.catch(err =>
sendResponse(res, "User already exists", 200)
return
)
function sendResponse(res, message, error)
res
.status(error !== null ? error !== null ? 400 : 200 : 400)
.json(
'message': message,
'error': error,
)
最后但并非最不重要的是我的 mySql.js 文件:
var mySql = require('mysql');
const query = sql =>
return new Promise( ( resolve, reject ) =>
let connection = mysql.createConnection(
host: 'localhost',
user: 'root',
password: '',
database: 'oauth2test'
);
console.log('test2');
connection.query( sql, ( err, rows ) =>
if ( err )
connection.end();
reject( err );
else
connection.end();
resolve( rows );
);
);
module.exports.query = query;
【问题讨论】:
【参考方案1】:您的 mySql.js 文件中有一个简单的错字:
线
var mySql = require('mysql');
应该替换为
var mysql = require('mysql');
除了查询代码在我的机器上运行正常:
var mysql = require('mysql');
const query = sql =>
return new Promise( ( resolve, reject ) =>
let connection = mysql.createConnection(
host: 'localhost',
user: 'root',
password: '',
database: 'oauth2test'
);
console.log('test2');
connection.query( sql, ( err, rows ) =>
if ( err )
connection.end();
reject( err );
else
connection.end();
resolve( rows );
);
);
module.exports.query = query;
【讨论】:
太好了,很高兴为您提供帮助。我相信你在回调上使用 Promises 是正确的,当你说“这种语法更像我的大脑工作”时,你说得很好:)。另请查看 async / await 语法,这又更具可读性。见developer.mozilla.org/en-US/docs/Web/javascript/Reference/…。以上是关于如何让我的 Node.js MySQL 连接作为承诺工作?的主要内容,如果未能解决你的问题,请参考以下文章
如何使用 Node.js 连接到我的 redshift 集群?