javascript - node js Express 连接mysql

标签 javascript mysql node.js express

这是我第一次在 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);

但是当我在 CMD >node app.js 中运行这个 app.js 文件时

我收到这个错误。

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

我无法弄清楚到底是什么问题。

最佳答案

您的代码是为 Express 3 编写的,而您似乎在使用 Express 4。

createServer 已被删除。

只需使用 express() 即可创建一个新应用。

引用:Migrating from Express 3 to Express 4

关于javascript - node js Express 连接mysql,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23625061/

相关文章:

javascript - 拼接删除错误的索引

mysql - Opencart Mysql查询订单超过1次的客户

javascript - 如何在 Javascript 中减少 JSON 解析对象原型(prototype)?

javascript - 如何从数组中提取特定的一段json

node.js - docker/nodejs/mongodb部署:MongooseError [MongooseServerSelectionError]:连接超时

javascript - 使用 php 在 Google 图表时间轴中自定义工具提示

javascript - 如果属性类型不同,V8 相同类型的两个对象的隐藏类不相同

javascript - 当元素包含类时如何选中复选框?

mysql - 与 "Create TABLE as"类似的功能,但要添加更多信息

php - 警告 : mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean 值