express - mysql - 引用错误 - 未定义查询

时间:2017-12-29 06:24:11

标签: mysql node.js express ecmascript-6 node-mysql

我是nodejs的新手,我正在尝试使用mysql数据库创建一个节点服务器。我创建了以下文件来建立连接。

connect.js

import mysql from 'mysql';
var db;

const connectDatabase = () => {
  if (!db) {
    db = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: 'root',
        port: '8889',
        database : 'testDb'
    });

db.connect(function(err){
  if(!err) {
      console.log('Database is connected!');
  } else {
      console.log('Error connecting database!', err);
  }
});


}
  return db;
}

export { connectDatabase, db};

server.js

import express from "express";
import bodyParser from "body-parser";
import cors from "cors";
import logger from './core/logger/app-logger'
import morgan from 'morgan'
import config from './core/config/config.dev'
import user from './routes/user.route'
import {connectDatabase} from './db/connect'

const port = config.serverPort;
logger.stream = {
    write: function(message, encoding){
        logger.info(message);
    }
};

connectDatabase();

const app = express();
app.use(cors());
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(morgan("dev", { "stream": logger.stream }));

app.use('/user', user);

//Index route
app.get('/', (req, res) => {
    res.send('Invalid endpoint!');
});

app.listen(port, () => {
    logger.info('server started - ', port);
});

user.route.js

import express from "express";
import userController from "../controllers/user.controller"
const router = express.Router()

router.get('/allUsers', (req, res) => {
    userController.getAll(req, res);
});

export default router;

user.controller.js

import userModel from '../models/user.model';
import logger from '../core/logger/app-logger';

let userController = {};

userController.getAll = (req, res) => {
    try {
            const users = userModel.getAll();
            logger.info('sending all users...');
            console.log('sending all users...');
            res.send(users);
    }
    catch(err) {
            logger.error('Error in getting users- ' + err);
            console.log('Error in getting users- ' + err);
            res.send('Got error in getAll');
    }
}


export default userController;

user.model.js

import { db } from '../db/connect'
import mysql from 'mysql';

const userModel = {};

userModel.getAll = () => {

    db.query("select * from user",query, function(err, results, query) {
    if (err) throw err;
    return results;
    });
}

export default userModel;

当我尝试运行userModel.getAll函数时,我希望'db'对象已经初始化(来自server.js)。

但是我从user.model.js

收到以下错误
Error in getting users- ReferenceError: query is not defined

我不确定我是否正在从connect.js

正确导出connectDatabase和db

我正在为项目使用ES6标准。任何帮助将不胜感激!

0 个答案:

没有答案