node.js - Connecting to database in Express -


trying connect database using express

  • i new express(i have used nodejs),
  • i trying connect database , display simple json resultant output
  • i tried below code

var express = require('express')   , http = require('http');  var app = express();  var connection = mysql.createconnection({         host: 'localhost',         user: 'root',         password: "root",         database: 'restaurant' });  // environments app.set('port', process.env.port || 7002);   app.get('/',function(request,response){ connection.query('select * restaurants', function(err, rows, fields)          {                 console.log('connection result error '+err);                 console.log('no of records '+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')); }); 

error::

var connection = mysql.createconnection({                  ^ referenceerror: mysql not defined 

error tells mysql module absent, have installed mysql module using::

npm install mysql  

still no change in error any ideas

you're missing mysql module.

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

but need connect():

connection.connect(); 

before start querying database.

all-together laziness:

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(); // <---- , here  // environments app.set('port', process.env.port || 7002);   app.get('/',function(request,response){ connection.query('select * restaurants', function(err, rows, fields)      {             console.log('connection result error '+err);             console.log('no of records '+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')); }); 

Comments

Popular posts from this blog

css - Which browser returns the correct result for getBoundingClientRect of an SVG element? -

gcc - Calling fftR4() in c from assembly -

Function that returns a formatted array in VBA -