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?
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)
When referenced in the browser under http: // localhost: 8080 / I can see the inscription Hello World with Express. I am trying to deposit the following application on heroku. I followed the tutorial on heroku.
1 )create new app
2) App name
3) region Europe
4) heroku login
5) $ cd my-project/
$ git init
$ heroku git:remote -a app-app
$ git add .
$ git commit -am "make it better"
$ git push heroku master
The application has been built, I am trying to run it I have an error:
Application error An error occurred in the application and your page
could not be served. If you are the application owner, check your logs
for details. You can do this from the Heroku CLI with the command
api-routes
// api-routes.js
// Initialize express router
let router = require('express').Router();
// Set default API response
router.get('/', function (req, res) {
res.json({
status: 'API Its Working',
message: 'Welcome to RESTHub crafted with love!',
});
});
// Import contact controller
var contactController = require('./contactController');
// Contact routes
router.route('/contacts')
.get(contactController.index)
.post(contactController.new);
router.route('/contacts/:contact_id')
.get(contactController.view)
.patch(contactController.update)
.put(contactController.update)
.delete(contactController.delete);
// Export API routes
module.exports = router;
contactController.js
// Import contact model
Contact = require('./contactModel');
// Handle index actions
exports.index = function (req, res) {
Contact.get(function (err, contacts) {
if (err) {
res.json({
status: "error",
message: err,
});
}
res.json({
status: "success",
message: "Contacts retrieved successfully",
data: contacts
});
});
};
// Handle create contact actions
exports.new = function (req, res) {
var contact = new Contact();
contact.name = req.body.name ? req.body.name : contact.name;
contact.gender = req.body.gender;
contact.email = req.body.email;
contact.phone = req.body.phone;
// save the contact and check for errors
contact.save(function (err) {
// Check for validation error
if (err)
res.json(err);
else
res.json({
message: 'New contact created!',
data: contact
});
});
};
// Handle view contact info
exports.view = function (req, res) {
Contact.findById(req.params.contact_id, function (err, contact) {
if (err)
res.send(err);
res.json({
message: 'Contact details loading..',
data: contact
});
});
};
// Handle update contact info
exports.update = function (req, res) {
Contact.findById(req.params.contact_id, function (err, contact) {
if (err)
res.send(err);
contact.name = req.body.name ? req.body.name : contact.name;
contact.gender = req.body.gender;
contact.email = req.body.email;
contact.phone = req.body.phone;
// save the contact and check for errors
contact.save(function (err) {
if (err)
res.json(err);
res.json({
message: 'Contact Info updated',
data: contact
});
});
});
};
// Handle delete contact
exports.delete = function (req, res) {
Contact.remove({
_id: req.params.contact_id
}, function (err, contact) {
if (err)
res.send(err);
res.json({
status: "success",
message: 'Contact deleted'
});
});
};
**contactModel.js**
var mongoose = require('mongoose');
// Setup schema
var contactSchema = mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true
},
gender: String,
phone: String,
create_date: {
type: Date,
default: Date.now
}
});
// Export Contact model
var Contact = module.exports = mongoose.model('contact', contactSchema);
module.exports.get = function (callback, limit) {
Contact.find(callback).limit(limit);
}
index.js
// Import express
let express = require('express');
// Import Body parser
let bodyParser = require('body-parser');
// Import Mongoose
let mongoose = require('mongoose');
// Initialize the app
let app = express();
// Import routes
let apiRoutes = require("./api-routes");
// Configure bodyparser to handle post requests
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
// Connect to Mongoose and set connection variable
mongoose.connect('mongodb://XXXX:XXXX#cluster0-shard-00-00-ov74c.mongodb.net:27017,cluster0-shard-00-01-ov74c.mongodb.net:27017,cluster0-shard-00-02-ov74c.mongodb.net:27017/test123456?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority', { useNewUrlParser: true});
var db = mongoose.connection;
// Added check for DB connection
if(!db)
console.log("Error connecting db")
else
console.log("Db connected successfully")
// Setup server port
var port = process.env.PORT || 8080;
// Send message for default URL
app.get('/', (req, res) => res.send('Hello World with Express'));
// Use Api routes in the App
app.use('/api', apiRoutes);
// Launch app to listen to specified port
app.listen(port, function () {
console.log("Running App on port " + port);
});
I solved it.
In package.json I added "start": "node index.js" to scripts
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1",
"start": "node index.js"
}
I have a simple registration page which should store the users input (name,email,password) in a database. I am using express and node. The thing i wanted to try is to have all the database operations (insert,select etc) for registration in one file and send the response to the server from another file.
dbQuery.js
var express=require("express");
var app = express();
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'user_name',
password : 'password',
database : 'database'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports.register=function(callback){
app.get('/register',function(req,res){
var today = new Date();
var users={
"name":req.body.name,
"email":req.body.email,
"password":req.body.password,
"created_at":today,
"updated_at":today
}
return connection.query('INSERT INTO users SET ?',users, callback)
}
}
app.js
var express=require("express");
var connection = require('./dbQuery');
var app = express();
app.post('/register',function(req,res){
connection.register(function(error, results, fields){
if (error) {
res.json({
status:false,
message:'there are some error with query for registration'
})
}else{
console.log('is it coming here in else')
res.json({
status:true,
data:results,
message:'user registered sucessfully'
})
}
})
})
index.html
<html>
<body>
<form action="/register" method="POST">
First Name: <input type="text" name="name">
Email: <input type="text" name="email">
Password: <input type="password" name="password">
<input type="submit" value="Submit">
</form>
</body>
</html>
When i execute app.js the server just keep loading without giving anything
I expected the output should be displaying the json response on server i.e 'user successfully registered' ,but it keeps on loading.
Try changing dbQuery.js to this:
var mysql = require("mysql");
var connection = mysql.createConnection({
host: "localhost",
user: "user_name",
password: "password",
database: "database"
});
connection.connect(function(err) {
if (!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
module.exports.register = function(callback) {
var today = new Date();
var users = {
name: req.body.name,
email: req.body.email,
password: req.body.password,
created_at: today,
updated_at: today
};
connection.query("INSERT INTO users SET ?", users, callback);
};
You are doing wrong, here if am posting simple steps for an API by express
Your app.js file should be
var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
const i18n = require("i18n");
var indexRouter = require('./routes/index');
// this is the api file created under the routes folder
var apiRouter = require('./routes/api');
require('./database')
var app = express();
app.use(i18n.init);
i18n.configure({
locales: ['en', 'de'],
cookie: 'LocalLang',
defaultLocale: 'en',
extension: ".json",
directory: __dirname + '/locales',
register: global,
logDebugFn: function (msg) {
console.log('debug', msg);
},
logWarnFn: function (msg) {
console.log('warn', msg);
},
logErrorFn: function (msg) {
console.log('error', msg);
}
});
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/api', apiRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('pages/error');
});
module.exports = app;
In you api.js file which is required in app.js file
var express = require('express');
var router = express.Router();
//Import your query.js file
const query = require('path for the file ./query')
router.post('/register',query.register)
module.exports = router;
query.js file should be like
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'user_name',
password : 'password',
database : 'database'
});
connection.connect(function(err){
if(!err) {
console.log("Database is connected");
} else {
console.log("Error while connecting with database");
}
});
exports.register = (req, res)=>{
var today = new Date();
var users = {
name: req.body.name,
email: req.body.email,
password: req.body.password,
created_at: today,
updated_at: today
};
connection.query("INSERT INTO users SET ?", users, (error,result)=>{
if(err)
return res.send({status:false, message:"Error in savind data in db"})
return res.send({status:true, message:"Resgistered sucessfully"})
});
}
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.
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