I am trying to connect to Sql Server Database using Node.js
Below is the code :
var express = require('express');
var sql = require('mssql');
var app = express();
app.get('/', function (req, res) {
var config = {
server: 'server',
database: 'database',
user: 'user',
password: 'password',
options: {
encrypt: true,
trustServerCertificate:false
}
};
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
console.log("preparing request");
request.query("some query").then(function (recordSet) {
if (err) console.log(err);
res.send(recordset);
});
});
});
app.listen(8080);
I get the log: "preparing request". After that nothing happens. There isn't any error log either.
In Java I connect to my DB using following URL:
jdbc:jtds:sqlserver://servername;SSL=request
Related
Below is my server.js file content. When I try to execute it, It takes too long and finally I am getting "Error in the query!" Although accounts table contains 1 row but still something seems to be wrong. Please can any one help me with it!
const express = require('express')
const app = express()
const mysql = require('mysql')
const db = mysql.createConnection({
host: 'localhost',
user: 'root',
password: '',
database: 'myDatabase',
port: '8090'
});
app.set('view-engine', 'ejs')
db.connect(function(error){
if(!error){
console.log('Error');
} else {
console.log('Connected');
}
})
app.get('/test', (req, res) => {
let sql ='SELECT * FROM accounts';
db.query(sql,function(error, rows, fields) {
if(!!error){
console.log('Error in the query!');
} else{
console.log('Successful query');
console.log(rows[0]);;
}
})
})
app.get('/', (req, res) => {
res.render('index.ejs')
app.on('close', function() {
db.end();
});
app.listen('3000', ()=>{
console.log('Server started on port 3000')
})
Edit:
I am getting this error:
Error in the query! Error: Cannot enqueue Query after fatal error.
at Protocol._validateEnqueue (E:\Screen Sharing App\InovantisMeets\node_modules\mysql\lib\protocol\Protocol.js:212:16)
at Protocol._enqueue (E:\Screen Sharing App\InovantisMeets\node_modules\mysql\lib\protocol\Protocol.js:138:13)
at Connection.query (E:\Screen Sharing App\InovantisMeets\node_modules\mysql\lib\Connection.js:198:25)
I'm fairly new to Node.js and I am having some issues.
im working on app for learning purposes but i came across this problem
Error: Can't render headers after they are sent to the client.
i didnt know how to make it work
C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^
Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:470:11)
at ServerResponse.header (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\express\lib\response.js:771:10)
at ServerResponse.send (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\express\lib\response.js:267:15)
at C:\Users\GameDev\Desktop\Portfolio\reciepe\routes\route.js:32:20
at Query. (C:\Users\GameDev\Desktop\Portfolio\reciepe\models\orm.js:9:9)
at Query. (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\Connection.js:525:10)
at Query._callback (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\Connection.js:491:16)
at Query.Sequence.end (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query.ErrorPacket (C:\Users\GameDev\Desktop\Portfolio\reciepe\node_modules\mysql\lib\protocol\sequences\Query.js:90:8)
SQL error :
code: 'ER_PARSE_ERROR',
errno: 1064,
sqlMessage:
'You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near \'NULL,
\'dqdd\'\' at line 1',
sqlState: '42000',
index: 0,
sql:
'INSERT INTO authentication(username,password) VALUES NULL, \'dqdd\'' }
here is the database
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "root",
password: "",
database:'reciepeapp'
});
module.exports = con
the ORM
const con = require('./db')
const orm = {
insertOne: function (values, cb) {
const sqlQuery = "INSERT INTO authentication(username,password) VALUES ?";
con.query(sqlQuery, [values],function (err, data) {
if (err) {
console.log(err)
cb(err, null);
} else {
cb(null, data);
}
});
},
}
module.exports = orm;
here is the route.js
const express = require('express');
const app = express()
const router = express.Router()
const bcrypt = require('bcrypt');
bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({ extended: true }));
const orm = require('../models/orm')
router.get('/',(req,res)=>
res.render('home')
)
router.get('/login',(req,res)=>
res.render('login')
)
router.get('/register',(req,res)=>
res.render('register')
)
router.post("/register", function (req, res) {
values = [
username = req.body.username,
password = req.body.password
];
orm.insertOne(values, function(error) {
if (error) {
return res.status(401).json({
message: 'Not able to add'
});
}
return res.json({
username: values.username,
password:values.password
});
});
});
module.exports = router
index.js
const express = require('express');
const app = express()
const bodyParser = require("body-parser");
const indexRouter = require('./routes/route')
const con = require('./models/db')
con.connect(function(err) {
if (err) {
return console.error('error: ' + err.message);
}
console.log('Connected to the MySQL server.');
});
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
var exphbs = require('express-handlebars');
console.log(__dirname)
app.use('/',express.static(__dirname + '/public'));
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');
app.use('/',indexRouter)
const PORT = 5000;
app.listen(PORT,()=>console.log('it started on 5000'))
May I know what is wrong with my code?
The problem is in your orm file. There the callback is getting called twice(in case err is true/has a value), which in-turn calls the res.json twice. Try changing the below
con.query(sqlQuery, [values],function (err, data) {
if (err) {
cb(err, null);
} else {
cb(null, data);
}
});
I am trying to view the first row of a table but I get the error
TypeError: pendingItem.callback is not a function
at client.connect
var express = require("express");
const {Pool} = require("pg");
var app = express();
var conStr = "postgres://postgres:password#localhost:5432/postgres";
const pool = new Pool();
app.get("/", function(req, res, next) {
pool.connect(conStr, function(err, client, done) {
if (err) {
console.log("not able to get connection " + err);
res.status(400).send(err);
}
client.query("SELECT * FROM Users where id= $1", [1], function(err, result) {
done();
if (err) {
console.log(err);
res.status(400).send(err);
}
res.status(200).send(result.rows);
});
});
});
On Postgres connection Pool using connectionString
First if you are choosing to connect to Postgres using connectionURI, you need to initialize Pool with connectionString param:
const pool = new Pool({
connectionString: connectionString,
})
Then when calling pool.connect you only need to pass callback function:
pool.connect((err, client, release) => {...});
Check documentation on Pooling and different ways of making a connection to Postgres using node-postgres package: here and here
In your case this, it should look like this:
var express = require("express");
const pg = require("pg");
const {Pool} = require("pg");
var app = express();
var conStr = "postgres://postgres:password#localhost:5432/postgres";
const pool = new Pool({
connectionString: conStr
});
app.get("/", function(req, res, next) {
pool.connect(function(err, client, done) {
if (err) {
console.log("not able to get connection " + err);
res.status(400).send(err);
}
client.query("SELECT * FROM Users where id= $1", [1], function(err, result) {
done();
if (err) {
console.log(err);
res.status(400).send(err);
}
res.status(200).send(result.rows);
});
});
});
I am trying to connect to MS SQL DB using Node JS But I am getting the following error.
{ ConnectionError: Login failed for user 'Gurpanth'.
at ConnectionError not connected
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
GetData(function (recordSet) {
res.render('index', {product: recordSet})
});
});
var Connection = require('tedious').Connection;
var config = {
userName: "Gurpanth",
password: "windowspassword",
server: "GURPANTH",
options: {
database: "NodeJSDb",
encrypt: true,
}
};
var connection = new Connection (config);
connection.on('connect', function(err){
console.log(err);
if(err!=null){
console.log("not connected");
}
else{
console.log("Connected")
connection.close();
};
});
module.exports = router;
The error message you gave indicates that your username and/or password are not correct. Does that user exist in SQL Server?
Below is code of Node.js for getting the data from SQL server but it give an error
"Global connection already exists. Call sql.close() first."
var express = require('express');
var app = express();
app.get('/', function (req, res) {
var sql = require("mssql");
var config = {
user: 'sa',
password: '',
server: '',
database: 'Test'
};
sql.connect(config, function (err) {
if (err) console.log(err);
var request = new sql.Request();
request.query('select * from TestTable', function (err, recordset) {
if (err) console.log(err)
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
You should add sql.close() to your code after sql.connect() and it should work.