我是NodeJS的新手,想将我的示例数据库与node js连接并获取结果。我已经完成以下步骤。
npm install mysql --save
在应用程序中安装我的SQL
该应用程序在没有SQL查询的情况下运行良好,并且能够在localhost上查看消息,但是在添加SQL连接时会产生问题并显示错误Cannot read property 'query' of undefined
。 我在app.js中的代码如下
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var mysql = require("mysql");
var bodyParser = require('body-parser');
var mysql= require('mysql');
var http = require('http');
var indexRouter = require('./routes/api/v1/index');
var usersRouter = require('./routes/api/v1/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/api/v1/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
//Database connection
app.use(function(req, res, next){
console.log('In');
res.locals.connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : 'q1w2e3r4t5',
database : 'users'
});
res.locals.connection.connect();
console.log('out');
next();
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
var server = http.createServer(app);
server.listen(4001);
在users.js中,我的代码如下:
router.get('/', function(req, res, next) {
res.locals.connection.query('SELECT * from userInfo', function (error, results, fields) {
if(error){
res.send(JSON.stringify({"status": 500, "error": error, "response": null}));
//If there is error, we send the error in the error section with 500 status
} else {
res.send(JSON.stringify({"status": 200, "error": null, "response": results}));
//If there is no error, all is good and response is 200OK.
}
});
});
帮助解决该问题:(:)
答案 0 :(得分:2)
尝试在指定user.js的路由之前放置连接数据库的代码:
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'pug');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//Database connection
app.use(function(req, res, next){
console.log('In');
res.locals.connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : 'q1w2e3r4t5',
database : 'users'
});
res.locals.connection.connect();
console.log('out');
next();
});
app.use('/', indexRouter);
app.use('/api/v1/users', usersRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
var server = http.createServer(app);
server.listen(4001);
答案 1 :(得分:1)
您尝试使用它的方式是作为中间件。这意味着每次有一个api调用时,都会建立与数据库的新连接。当存在大量并行请求时,这将与数据库建立大量连接。理想情况下,您应该只创建一个连接并在整个应用程序中使用它。
创建一个新文件dbconnection.js
//create connection
let connection = mysql.createConnection({
host : '127.0.0.1',
user : 'root',
password : 'q1w2e3r4t5',
database : 'users'
});
//export connection, you can optionally use
//connection.connect here. The same state of this module is passed everywhere.
exports.connection = connection;
现在在您的app.js
中,使用var connection = require('./dbconnection');
导入此文件,这将自动创建连接。
您现在可以使用中间件在res.locals中设置连接,但是请记住在路由文件之前使用它。
app.use(function(req, res, next){
console.log('In');
res.locals.connection = connection
console.log('out');
next();
});
...
app.use('/', indexRouter);
app.use('/api/v1/users', usersRouter);
这应该完成工作。
答案 2 :(得分:0)