Trouble making nodejs mysql connection - javascript

I am trying to make a simple connection between my nodejs server and my mysql db (using Microsoft SQL server manager studio v14), below is my code and the error message appearing in my console window.
here is my code:
var express = require('express');
var app = express();
var sql = require("mssql");
app.get('/', function (req, res) {
// config for your database
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX'
};
// connect to your database
sql.connect(config, function (err) {
if (err) console.log(err);
// create Request object
var request = new sql.Request();
// query to the database and get the records
request.query('select * from Schools', function (err, recordset) {
if (err) console.log(err)
// send records as a response
res.send(recordset);
});
});
});
var server = app.listen(5000, function () {
console.log('Server is running..');
});
The error I am getting looks like this:
Server is running..
tedious deprecated The default value for `options.encrypt` will change from `false` to `true`. Please pass `false` explicitly if you want to retain current behaviour. node_modules\mssql\lib\tedious.js:212:23
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.tedious.once.err (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\tedious.js:216:17)
at Object.onceWrapper (events.js:275:13)
at Connection.emit (events.js:182:13)
at Connection.socketError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:1004:14)
at C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:869:25
at SequentialConnectionStrategy.connect (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:154:9)
at Socket.onError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:170:16)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
code: 'ESOCKET',
originalError:
{ ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\errors.js:12:12)
at Connection.socketError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:1004:30)
at C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connection.js:869:25
at SequentialConnectionStrategy.connect (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:154:9)
at Socket.onError (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\tedious\lib\connector.js:170:16)
at Socket.emit (events.js:182:13)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:59:3)
at process._tickCallback (internal/process/next_tick.js:174:19)
message: 'Failed to connect to localhost:1433 - Could not connect (sequence)',
code: 'ESOCKET' },
name: 'ConnectionError' }
{ ConnectionError: Connection is closed.
at Request._query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:1299:37)
at Request._query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\tedious.js:497:11)
at Request.query (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:1242:12)
at C:\Users\smr09\Desktop\Code\ou\db_test\test.js:24:17
at _poolCreate.then.catch.err (C:\Users\smr09\Desktop\Code\ou\db_test\node_modules\mssql\lib\base.js:269:7)
at process._tickCallback (internal/process/next_tick.js:178:7) code: 'ECONNCLOSED', name: 'ConnectionError' }
I am rather new at this particularly with dealing with databases. Can someone explain what the error means?

Add this line to the config:
options: {
encrypt: false
}
It will finally look like:
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX' ,
options: {
encrypt: false
}
};

try to put encrypt: false in your config{}, it will work.

your error:
ConnectionError: Failed to connect to localhost:1433 - Could not
connect (sequence)
My problem was resolved by adding port
var config = {
user: 'superadmin',
password: '***',
server: 'localhost',
database: 'XXX',
port: '',
};

Related

Bit.io randomly terminating connecting with node.js

Bit.io randomly terminates connecting with node.js.
When I try to run the following code my node.js works fine for a few minutes but then randomly crashes and gives the error listed at the bottom of this page. I have tried to fix this but I am stuck. Don't know if it's a problem with bit.io or with me. Thanks!!
Code:
const { Client } = require('pg');
const client = new Client({
user: 'process.env.USER',
host: 'db.bit.io',
database: 'process.env.DATABASE',
password: 'process.env.PASSWORD',
port: 5432,
ssl: true,
});
client.connect();
client.query('SELECT * FROM "HPI_AT_state" limit 10;', (err, res) => {
console.table(res.rows);
})
Error:
node:events:491
throw er; // Unhandled 'error' event
^
Error: Connection terminated unexpectedly
at Connection.<anonymous> (node_modules/pg/lib/client.js:132:73)
at Object.onceWrapper (node:events:627:28)
at Connection.emit (node:events:513:28)
at TLSSocket.<anonymous> (node_modules/pg/lib/connection.js:107:12)
at TLSSocket.emit (node:events:525:35)
at endReadableNT (node:internal/streams/readable:1359:12)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
Emitted 'error' event on Client instance at:
at Client._handleErrorEvent (node_modules/pg/lib/client.js:319:10)
at Connection.<anonymous> (node_modules/pg/lib/client.js:149:16)
at Object.onceWrapper (node:events:627:28)
[... lines matching original stack trace ...]
at process.processTicksAndRejections (node:internal/process/task_queues:82:21)
I have figured out the problem. It seems that the issue was because Bit.io terminates the connection if unused for 60 seconds. It was fixed by using Client instead of Pool.
const { Pool } = require('pg');
const pool = new Pool({
user: process.env.USER,
host: 'db.bit.io',
database: process.env.DATABASE,
password: process.env.PASSWORD,
port: 5432,
ssl: true,
});
pool.query('SELECT * FROM "SaveData" limit 10;', (err, res) => {
console.table(res.rows);
});

Connection between MariaDB and NodeJS not working

I'm using a vServer from Ionos for a little project. I installed a MariaDB and NodeJS. Currently I'm trying to connect them both. Here is my code:
const mariadb = require('mariadb');
const pool = mariadb.createPool({
host: 'localhost',
user:'root',
password: 'xxxxxxxxx',
database: 'christmastrees',
connectionLimit: 5,
});
async function asyncFunction() {
let conn;
try {
conn = await pool.getConnection();
const rows = await conn.query("SELECT * from bäume");
console.log(rows); //[ {val: 1}, meta: ... ]
} catch (err) {
throw err;
} finally {
if (conn) return conn.end();
}
}
But when executing the file (node app), I get an error message after a few seconds
Error: connect ECONNREFUSED 127.0.0.1:3306
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1157:16)
From event:
at _registerHandshakeCmd (/root/server/node_modules/mariadb/lib/connection.js:745:11)
at /root/server/node_modules/mariadb/lib/connection.js:57:11
at new Promise (<anonymous>)
at Connection.connect (/root/server/node_modules/mariadb/lib/connection.js:56:16)
at createConnectionPoolPromise (/root/server/node_modules/mariadb/lib/pool-promise.js:31:8)
at creationTryout (/root/server/node_modules/mariadb/lib/pool-base.js:373:9)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 3306,
fatal: true
}
So I searched for help and after 2 hours I literally found only one Idea. I added this line of code to my connection...
port: '/var/run/mysqld/mysqld.sock'
I tryed again to use node app, but this time I didn't get an error message, it is loading forever and nothing happens.
I would be so grateful for any help...
So I found the solution to my problem.
I checked if my MariaDB Service is even running and no it wasn't ^^

my express endpoint route with mysql logs an error: connect ECONNREFUSED 127.0.0.1

I'm building a web app for a bootcamp. I'm using express and mysql. I'm routing a get request to an endpoint. The route should query my mysql database table to select all. I'm expecting to send the result to the chrome page. Instead I get this error:
Error: connect ECONNREFUSED 127.0.0.1:8211
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1054:14)
--------------------
at Protocol._enqueue (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/protocol/Protocol.js:144:48)
at Protocol.handshake (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/protocol/Protocol.js:51:23)
at Connection.connect (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/Connection.js:119:18)
at Connection._implyConnect (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/Connection.js:457:10)
at Connection.query (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/mysql/lib/Connection.js:199:8)
at Object.getAllUsers (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/database/index.js:17:14)
at /Users/cnebs/Documents/HRATX/hratx42-fullstack-review/server/index.js:22:6
at Layer.handle [as handle_request] (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/express/lib/router/layer.js:95:5)
at next (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/express/lib/router/route.js:137:13)
at Route.dispatch (/Users/cnebs/Documents/HRATX/hratx42-fullstack-review/node_modules/express/lib/router/route.js:112:3) {
errno: 'ECONNREFUSED',
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8211,
fatal: true
}
I'm able to query the database in terminal. I'm able to send text to the page on chrome through express. I've built a database and table. I haven't used the api for my project to populate the table yet. My console is logging the error through a function in my database index which I've imported to express to be used in the get route.
Here is the database index:
const mysql = require('mysql');
const connection = mysql.createConnection({
host: "127.0.0.1",
user: "root",
password: "password",
database: "github",
port: 8211
});
const test = () => {
connection.query("DESCRIBE git_repos", (err, res) => {
console.log('selection: ', res)
})
}
const getAllUsers = cb => {
connection.query(`select * from todos`, (err, res) => {
if (err) {
console.log("error in getAllUsers: ", err);
cb(err);
} else {
cb(null, res);
}
});
}
module.exports = { test, getAllUsers }
Here is the server index:
const express = require('express');
const db = require('../database')
let app = express();
app.use(express.static(__dirname + '/../client/dist'));
app.get('/repos', function (req, res) {
// TODO - your code here!
// This route should send back the top 25 repos
db.getAllUsers((err, result) => {
if (err) {
console.error(err)
res.status(404).end();
} else {
console.log('Getting')
res.send(result)
}
})
});
let port = 1128;
app.listen(port, function() {
console.log(`listening on port ${port}`);
});
I expect to see any result at all from my query delivered to the page from the res.send.
Instead, I see that the localhost page can't be found and the err response above in my server terminal.
You aren't able to directly choose the port for your database server in the createConnection(). Remove the port property and it will function.

Connect ssh server through nodejs code with ssh key and server name

I have vpn access, so i can ssh to server by following command from terminal
ssh qa-trinath01.my-qa
Its working fine from terminal.
But from nodejs, its not working. my code is
var express = require("express");
var app = express();
var node_ssh = require('node-ssh')
var
ssh = new node_ssh()
ssh.connect({
host: 'qa-trinath01.my-qa',
username: 'tanantham',
port: 27017,
privateKey: '/Users/tanantham/.ssh/id_rsa'
}).then(function() {
console.error('Success: ');
}).catch((error) => {
console.error('ERROR: ', error);
});;
app.listen(3001);
I am getting output as
ERROR: { Error: getaddrinfo ENOTFOUND qa-trinath01.my-qa qa-trinath01.my-qa:27017
at errnoException (dns.js:50:10)
at GetAddrInfoReqWrap.onlookup [as oncomplete] (dns.js:92:26)
code: 'ENOTFOUND',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'qa-trinath01.my-qa',
host: 'qa-trinath01.my-qa',
port: 27017,
level: 'client-socket' }
Can some one suggest the nodejs code to connect to ssh, i have only ssh key and ssh server name details.
ssh key -> /Users/tanantham/.ssh/id_rsa
server name -> qa-trinath01.my-qa
Have you tried to replace 'privateKey' with 'password' and enter your password.
It's probably not the most secure but it normally works.
Unless you have to use your private key from id-rsa
ssh = new node_ssh()
ssh.connect({
host: 'qa-trinath01.my-qa',
username: 'tanantham',
port: 27017,
password: 'YourPasswordHere'
}).then(function() {
console.error('Success: ');
}).catch((error) => {
console.error('ERROR: ', error);
});;
app.listen(3001);

nodemailer google smtp connection closed error

I am trying to send email using nodemailer and nodemailer-smtp-transport in express js. i am creating a custom module to send mails to the user. When ever i am executing the script it is throwing 2 specific errors.
Error 1
D:\Projects\project_name\modules\mailer.js:45
throw error;
^
Error: Connection closed
at SMTPConnection.<anonymous> (D:\Projects\WISSENX\node_modules\nodemailer-smtp-transport\lib\smtp-transport.js:113:29)
at SMTPConnection.g (events.js:260:16)
at emitNone (events.js:67:13)
at SMTPConnection.emit (events.js:166:7)
at SMTPConnection._destroy (D:\Projects\WISSENX\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\lib\smtp-connection.js:558:10)
at SMTPConnection._onEnd (D:\Projects\WISSENX\node_modules\nodemailer-smtp-transport\node_modules\smtp-connection\lib\smtp-connection.js:538:10)
at Socket.g (events.js:260:16)
at emitNone (events.js:72:20)
at Socket.emit (events.js:166:7)
at endReadableNT (_stream_readable.js:921:12)
at nextTickCallbackWith2Args (node.js:442:9)
at process._tickCallback (node.js:356:17)
Error 2
{
[Error: getaddrinfo ENOTFOUND smtp.gmail.com smtp.gmail.com:465]
code: 'ECONNECTION',
errno: 'ENOTFOUND',
syscall: 'getaddrinfo',
hostname: 'smtp.gmail.com',
host: 'smtp.gmail.com',
port: '465',
command: 'CONN' }
My Complete code is
var nodemailer = require('nodemailer');
var smtpTransport = require("nodemailer-smtp-transport")
var constants = require('./../modules/constants');
/*var smtpTransport = nodemailer.createTransport(constants.MAIL_HOST,{
service : "Gmail",
auth: {
user: constants.MAIL_FROM_AUTH,
pass: constants.MAIL_PASSWORD
}
});*/
var smtpTransport = nodemailer.createTransport(smtpTransport({
host : constants.MAIL_HOST,
secureConnection : constants.MAIL_SECURE,
port: constants.MAIL_PORT,
auth : {
user : constants.MAIL_FROM_AUTH,
pass : constants.MAIL_PASSWORD
},
ignoreTLS: true
}));
var sendMail = function(req, res, template, to, subject, callback) {
var mailOptions = {
from: constants.MAIL_FROM, // sender address
to: to, // list of receivers
subject: subject, // Subject line
text: "random text", // plaintext body
html: template // html body
}
console.log(mailOptions);
console.log(smtpTransport);
// send mail with defined transport object
smtpTransport.sendMail(mailOptions, function(error, response){
console.log("Message sent: " + response);
console.log(error);
if(error) {
throw error;
console.log(error);
}
else {
console.log("Message sent: " + response.message);
}
smtpTransport.close(); // shut down the connection pool, no more messages
});
}
exports.sendMail = sendMail;

Categories

Resources