无法将db连接作为模块:Nodejs

时间:2018-01-27 05:53:00

标签: node.js express module

我正在尝试封装我的数据库连接。为此,我在根目录中有一个名为connection.js的模块,其中包含以下代码:

var mysql = require('mysql');
// Establishing connection with database
var connection = mysql.createConnection({
    host: '127.0.0.1',
    user: 'root',
    password: '',
    database: 'SMS'
});
connection.connect(function(err){
    if (err) {
      console.log('Error establishing connection with database. ' + err);
    } else {
      console.log('Connection established with database');
    }
  });

module.exports = connection;

我的index.js文件中我想使用这个模块。

var express = require('express');
var reload = require('reload');
var db = require('./connection');
var router = express.Router();

router.get('/addStudent', function(req, res){
  res.render('addStudent', {
    title: 'Add student'
  });
});


router.post('/add', function(req, res){
  var q = "INSERT INTO `students` (`id`, `name`, `fname`, `class`, `age`, `gender`, `contact`, `address`, `image`, `date`) VALUES (NULL, '" + req.body.name + "', '" + req.body.fname + "', '" + req.body.class + "', '" + req.body.age + "', 'Male', " + req.body.contact + ", 'House# e-13, Sec. 4/F, Zia colony, Orangi town, Karachi.', 'suleman.jpg', 'Jun, 2017')";
  db.query(q, function(err, result){
    if (err) {
      console.log('Error querying the database. ' + err);
    } else {
      console.log('Record inserted successfully');
    }
  });
});

module.exports = router;

抛出以下错误:

  

错误:找不到模块'./connection'

我不知道我哪里出错了。谁能帮我解决这个问题?

1 个答案:

答案 0 :(得分:0)

connection.js

module.exports = {
connect: function (callback) {

        mysql = require('mysql');

        this.dbh = mysql.createConnection({
              host: '127.0.0.1',
              user: 'root',
              password: '',
              database: 'SMS'
        });

        this.dbh.connect(function (err) {

            if (err) {
                console.log(err);
                callback(false);

            } else {
                callback(true);
            }
        });


}

index.js

var my = require('./connection');

my.connect(function (cb) {
    if (cb) {
        console.log('mysql conncted');
    } else {
        console.log('mysql connect failed.');
        process.exit(1);
    }
});