I am working on a sample application using Node js and SQL server 2008.
To access SQL server from node js am using seriate [http://developer.leankit.com/painless-sql-server-with-nodejs-and-seriate/].
Below is my sample code
File ./DBLayer/db.js code
var sql = require("seriate");
var config = {
"server": "127.0.0.1",
"user": "sa",
"password": "12kafour~9999",
"database": "Tickets"
};
sql.setDefaultConfig( config );
exports.sqlDb = sql;
And file app.js code
var express = require('express');
var app = express();
var path = require('path');
var bodyParser = require('body-parser');
var sqlDb = require('./DBLayer/db.js');
//-- set the view engine
app.set('view engine' , 'ejs');
app.use( bodyParser.json() ); // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({ // to support URL-encoded bodies ??
extended: true
}));
//-- set the routes
app.get('/login' , function(req , res){
//-- set the view to render
res.render('login' , {title:'Login Screen' , error : ''});
});
app.post('/login' , function(req , res) {
sqlDb.execute( {
query: "SELECT count(*) FROM USERS WHERE LOGIN ='" + req.body.username + "'" + "AND PASSWORD = '" + req.body.pwd + "'"
} ).then( function( results ) {
res.render('login' , {title:'Login Screen' , error : 'u r the one...'});
}, function( err ) {
res.render('login' , {title:'Login Screen' , error : 'Invalid Login/Password.'});
});
});
//-- set the port
var server = app.listen(3000 , function() {
console.log('Server Ready..')
});
When user enters username and password and submits am getting "TypeError: sqlDb.execute is not a function" error.
I am not sure why I am getting this error.
You should change this line:
var sqlDb = require('./DBLayer/db.js');
to
var sqlDb = require('./DBLayer/db.js').sqlDb;
or to change this line:
exports.sqlDb = sql;
to
exports = sql;
Explanation: In Node when you do:var sqlDb = require('./DBLayer/db.js');
it make sqlDb to be the exports
object.
So in your code you have exports.sqlDb = sql
. The compiler is right exports don't have execute function. exports only have 1 var, exports.sqlDb
.
Bonus Tip: If you really want you code to work, without change app.js
you can add this to the end of your module:
exports.execute=function(){
return sql.execute.call(sql,arguments)
}