我无法将mysql连接文件从父文件导入另一个文件以建立数据库连接。
如果查询是在同一文件中写入的,我可以连接到DB,如果我尝试在另一个文件中命中相同的查询,则会收到“ TypeError:connection.query不是函数”错误。无法访问连接对象的任何功能。
这是我的server.js文件:
var express = require('express');
var cors = require('cors');
var mysql = require('mysql');
app = express(),
app.use(cors()),
port = process.env.PORT || 3001;
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
config = {
host: 'localhost',
user: 'root',
password: '',
database: '<DB name>'
}
var connection = mysql.createConnection(config);
connection.connect(function(err){
if (err){
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
});
var routes = require('./api/routes/routes'); //importing route
routes(app);
console.log('todo list RESTful API server started on: ' + port);
app.listen(port);
module.exports= connection;
这是我的api.js文件:
'use strict';
var connection = require('../../server.js');
connection.query ('select * from <table name>', function(error, results){
if (results){
console.log(results);
}
else{
console.log(error);
}
});
or
exports.get=function(req,res){
console.log(req.query.printerModel);
console.log('inside get function');
connection.query('select * from inkdetails', function(error, results){
if (results){
res.status(200).send(inkdetails)
console.log(results);
}
else{
res.status(400).send(error)
console.log(error);
}
});
};
答案 0 :(得分:2)
创建一个配置文件夹并创建一个文件databaseConfig.js
var mysql = require('mysql');
config = {
host: 'localhost',
user: 'root',
password: '',
database: '<DB name>'
}
var connection =mysql.createConnection(config); //added the line
connection.connect(function(err){
if (err){
console.log('error connecting:' + err.stack);
}
console.log('connected successfully to DB.');
});
module.exports ={
connection : mysql.createConnection(config)
}
app.js
var express = require('express');
var cors = require('cors');
app = express(),
app.use(cors()),
port = process.env.PORT || 3001;
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
var routes = require('./api/routes/routes'); //importing route
routes(app);
console.log('todo list RESTful API server started on: ' + port);
app.listen(port);
controller.js
var config = require('../../databaseConfig.js');
var connection= config.connection
connection.query ('select * from <table name>', function(error, results){
if (results){
console.log(results);
}
else{
console.log(error);
}
});
答案 1 :(得分:1)
创建一个文件来处理连接并导出与mysql
相关的实用程序功能,然后可以在启动文件中初始化连接并将该连接对象导入任何处理程序中。
您的mysql
库:
const mysql = require('mysql');
const logger = require('your-looger-path');
const mysqlConfig = {
host: 'localhost',
user: 'root',
password: '',
database: '<DB name>'
}
var pool = mysql.createPool(mysqlConfig);
module.exports.connect = function (cb) {
return new Promise((resolve, reject) => {
pool.on('connection', function (connection) {
connection.on('error', function (err) {
logger.error('MySQL error event', err)
});
connection.on('close', function (err) {
logger.warn('MySQL close event', err)
});
});
resolve()
})
}
async function executeQuery (query) {
logger.debug(`query: `, query)
return new Promise((resolve, reject) => {
try{
pool.query(query, (e, r, f) => {
if(e){
reject(e)
}
else{
logger.debug(r,f)
resolve(r[0])
}
});
}
catch(ex){
reject(ex)
}
})
}
async function execSP(spName, params){
return new Promise((resolve, reject) => {
try{
var paramPlaceHolder = ''
if(params && params.length){
for(var i = 0; i < params.length; i++){
paramPlaceHolder += '?,'
}
}
if(paramPlaceHolder.length){
paramPlaceHolder = paramPlaceHolder.slice(0, -1)
}
logger.debug('final SP call', `CALL ${spName}(${params})`)
pool.query(`CALL ${spName}(${paramPlaceHolder})`, params, (e, r, f) => {
if(e){
reject(e)
}
else{
resolve(r[0])
}
});
}
catch(ex){
reject(ex)
}
})
}
module.exports.executeQuery = executeQuery
module.exports.execSP = execSP
,然后在server.js
文件中创建连接:
var express = require('express');
var cors = require('cors');
var mysqllib = require('require to your mysql wrapper created above');
app = express(),
app.use(cors()),
port = process.env.PORT || 3001;
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
mysqllib.connect().then(() => {
console.log('Connected to mysql...')
var routes = require('./api/routes/routes'); //importing route
routes(app);
console.log('todo list RESTful API server started on: ' + port);
app.listen(port);
}).catch(e => {
console.error('Error connecting mysql...')
process.exit()
})
在您的控制器中
'use strict';
const mysqlLib = require('your mysql lib path')
exports.get = function(req, res){
console.log(req.query.printerModel);
console.log('inside get function');
mysqlLib.executeQuery('select * from inkdetails').then((d) => {
console.log(d);
res.status(200).send(d)
}).catch(e => {
console.log(e);
res.status(500).send('Sorry, something went wrong!')
})
};
希望这对您有所帮助。