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
错误仍未改变 任何想法
答案 0 :(得分: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'));
});