简体   繁体   English

node js Express mysql 连接

[英]node js Express mysql connection

this is very first time i am writing in node (Express) js, i am trying to connect my database (Mysql).Here what i found the code for my app.js file.这是我第一次在 node (Express) js 中编写代码,我正在尝试连接我的数据库 (Mysql)。在这里我找到了我的app.js文件的代码。

app.js

var express = require('express'),
mysql = require('mysql');

// Application initialization

var bodyParser = require('body-parser');

var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : ''
});
var app = module.exports = express.createServer();

// Database setup

connection.query('CREATE DATABASE IF NOT EXISTS test', function (err) {
if (err) throw err;
connection.query('USE test', function (err) {
if (err) throw err;
connection.query('CREATE TABLE IF NOT EXISTS users('
+ 'id INT NOT NULL AUTO_INCREMENT,'
+ 'PRIMARY KEY(id),'
+ 'name VARCHAR(30)'
+ ')', function (err) {
if (err) throw err;
});
});
});

// Configuration

app.use(express.bodyParser());

// Main route sends our HTML file

app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});

// Update MySQL database

app.post('/users', function (req, res) {
connection.query('INSERT INTO users SET ?', req.body,
function (err, result) {
if (err) throw err;
res.send('User added to database with ID: ' + result.insertId);
}
);
});

// Begin listening

app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

but when i am running this app.js file in CMD >node app.js但是当我在 CMD >node app.js 中运行这个 app.js 文件时

i get this error.我收到这个错误。

c:\express\testproject>node app.js

c:\express\testproject\app.js:13
var app = module.exports = express.createServer();
                                   ^
TypeError: Object function createApplication() {
  var app = function(req, res, next) {
    app.handle(req, res, next);
  };

  mixin(app, proto);
  mixin(app, EventEmitter.prototype);

  app.request = { __proto__: req, app: app };
  app.response = { __proto__: res, app: app };
  app.init();
  return app;
} has no method 'createServer'
    at Object.<anonymous> (c:\express\testproject\app
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:1
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

I am unable to figure out what exactly the issue is.我无法弄清楚到底是什么问题。

You seem to be using Express 4 while your code is written for Express 3.您似乎在使用 Express 4,而您的代码是为 Express 3 编写的。

createServer has been removed. createServer已被删除。

Just use express() to create a new app.只需使用express()创建一个新应用程序。

Reference : Migrating from Express 3 to Express 4参考: 从 Express 3 迁移到 Express 4

this is very first time i am writing in node (Express) js, i am trying to connect my database (Mysql).Here what i found the code for my app.js file.这是我第一次使用节点(Express)js编写代码,试图连接数据库(Mysql)。在这里,我找到了app.js文件的代码。

app.js

var express = require('express'),
mysql = require('mysql');

// Application initialization

var bodyParser = require('body-parser');

var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : ''
});
var app = module.exports = express.createServer();

// Database setup

connection.query('CREATE DATABASE IF NOT EXISTS test', function (err) {
if (err) throw err;
connection.query('USE test', function (err) {
if (err) throw err;
connection.query('CREATE TABLE IF NOT EXISTS users('
+ 'id INT NOT NULL AUTO_INCREMENT,'
+ 'PRIMARY KEY(id),'
+ 'name VARCHAR(30)'
+ ')', function (err) {
if (err) throw err;
});
});
});

// Configuration

app.use(express.bodyParser());

// Main route sends our HTML file

app.get('/', function(req, res) {
res.sendfile(__dirname + '/index.html');
});

// Update MySQL database

app.post('/users', function (req, res) {
connection.query('INSERT INTO users SET ?', req.body,
function (err, result) {
if (err) throw err;
res.send('User added to database with ID: ' + result.insertId);
}
);
});

// Begin listening

app.listen(3000);
console.log("Express server listening on port %d in %s mode", app.address().port, app.settings.env);

but when i am running this app.js file in CMD >node app.js但是当我在CMD> node app.js中运行此app.js文件时

i get this error.我得到这个错误。

c:\express\testproject>node app.js

c:\express\testproject\app.js:13
var app = module.exports = express.createServer();
                                   ^
TypeError: Object function createApplication() {
  var app = function(req, res, next) {
    app.handle(req, res, next);
  };

  mixin(app, proto);
  mixin(app, EventEmitter.prototype);

  app.request = { __proto__: req, app: app };
  app.response = { __proto__: res, app: app };
  app.init();
  return app;
} has no method 'createServer'
    at Object.<anonymous> (c:\express\testproject\app
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:1
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)
    at startup (node.js:119:16)
    at node.js:902:3

I am unable to figure out what exactly the issue is.我无法弄清楚到底是什么问题。

has no method 'createServer'. 

This explains you the reason.这解释了你的原因。 So your line of code所以你的代码行

var app = module.exports = express.createServer();

is not a valid call.不是有效调用。 So as explained above you have Express 4 on your working directory and you have called the method that belongs to Express 3.因此,如上所述,您的工作目录中有 Express 4,并且您调用了属于 Express 3 的方法。

var app = express();

first install mysql module首先安装mysql模块

npm install mysql –save

then create a file db.js or the name u prefer.然后创建一个文件 db.js 或您喜欢的名称。

import mysql from 'mysql';
var connection = mysql.createConnection({
    host: 'DB_host',
    user: 'DB_user',
    password: 'DB_password',
    database:'DB_name'
});

connection.connect(function(err) {
    if (err) {
        console.error('error connecting: ' + err.stack);
        return;
    }
    console.log('data base connected as id ' + connection.threadId);
});

connection.on('error', function(err) {
    console.log('db error normal;', err);
    if(err.code === 'PROTOCOL_CONNECTION_LOST') {
        console.log('connect lost');                        
    } 
    else {                                     
        throw err;                                 
    }
});

//keep active your database connection

setInterval(function () {
    console.log('timeout completed'); 
    var sql="select id from table_name limit 1";
    connection.query(sql, function(err, result, field){
        console.log('running query for non idle ');
    });
}, 600000); 

module.exports = {connection, mysql};

you can use sequlize你可以使用 sequelize

const sequelize = new Sequelize(env.database, env.username, env.password, {
host: env.host,

 dialect: env.dialect,
 operatorsAliases: 1,

pool: {
  max: env.max,
  min: env.pool.min,
  acquire: env.pool.acquire,
  idle: env.pool.idle
}
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM