0

尝试使用 Express 连接到数据库

  • 我是 Express 新手(我使用过 NODEJS),
  • 我正在尝试连接到数据库并显示一个简单的 JSON 作为结果输出
  • 我尝试了下面的代码

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

var app = express();

var connection = mysql.createConnection({
        host: 'localhost',
        user: 'root',
        password: "root",
        database: 'restaurant'
});

// all environments
app.set('port', process.env.PORT || 7002);


app.get('/',function(request,response){
connection.query('SELECT * FROM restaurants', function(err, rows, fields)

        {
                console.log('Connection result error '+err);
                console.log('no of records is '+rows.length);
                        response.writeHead(200, { 'Content-Type': 'application/json'});
                response.end(JSON.stringify(rows));
        });

} );

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});

错误::

var connection = mysql.createConnection({
                 ^
ReferenceError: mysql is not defined

错误告诉 mysql 模块不存在,但我已经安装了 mysql 模块使用::

npm install mysql 

错误仍然没有变化 任何想法

4

1 回答 1

2

您缺少mysql模块。

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

但您还需要connect()

connection.connect();

在开始查询数据库之前。

现在一起懒惰:

var express = require('express')
  , http = require('http')
  , mysql = require('mysql'); // <---- HERE

var app = express();

var connection = mysql.createConnection({
    host: 'localhost',
    user: 'root',
    password: "root",
    database: 'restaurant'
});

connection.connect(); // <---- AND HERE

// all environments
app.set('port', process.env.PORT || 7002);


app.get('/',function(request,response){
connection.query('SELECT * FROM restaurants', function(err, rows, fields)

    {
            console.log('Connection result error '+err);
            console.log('no of records is '+rows.length);
                    response.writeHead(200, { 'Content-Type': 'application/json'});
            response.end(JSON.stringify(rows));
    });

} );

http.createServer(app).listen(app.get('port'), function(){
  console.log('Express server listening on port ' + app.get('port'));
});
于 2013-08-09T14:44:28.700 回答