Connect to mysql on correct port JS - javascript

hey using a javascript app im making as a backend server for my website i keep getting this as an error when trying to connect to my mysql server.
ConnectionError: Failed to connect to win2k16-mcdmz:1433 - Could not connect (sequence)
and this is my script to connect to the server. is there any ideas on why it is set to 1433?
private initializeServer() {
const config = {
user: 'MCAdmin',
password: '*******',
server: 'win2k16-mcdmz',
port: 3306,
database: 'ValorantLFG',
encrypt: true
};
mysql.connect(config, (err) => {
if (err) { console.log(err); }
this.init.lfgRequestsTimeout();
//this.init.noticesTimeout();
});
}

Related

Node.js MySQL Connection Error. ECONNREFUSED

I have 2 servers, one running the frontend code (Node.js, express) and the other running MySQL with PHPMyAdmin, both are working standalone and I can confirm the MySQL database is running on 3306 but whenever I try to connect via Node.js (code below) I get a connection refused error.
const conn = mysql.createConnection({
host: '192.168.1.250',
user: 'mcd',
password: '**********',
database: 'mcd'
})
conn.connect(function(err) {
if (err) throw err;
})
The IP address I have used for the host is the IP address of the MySQL server. So unsure why it cannot connect since it is running on the default port.
Here is my connection to Node.js:
pool = mysql.createPool({host:"localhost"
,port:"3306"
,database:"db_name"
,user:"user_name"
,password:"password_for_user"
,timezone:"utc"
,multipleStatements:true
,max:1000
,min:1
,idleTimeoutMillis:defs.QUERY_TIMEOUT});
if ( pool && pool.getConnection ) {
pool.getConnection(function(errsts, conn) {
var resp = {};
if ( errsts ) {
resp['error'] = errsts;
return;
}
resp['state'] = "connected";
if ( cbRoutine ) {
cbRoutine(conn, resp, objParams);
if ( conn != undefined ) {
conn.release();
}
}
});
}
localhost is correct for my usage, you should replace its your name or IP address.
defs.QUERY_TIMEOUT is defined in my source as:
var QUERY_TIMEOUT = 10 * 1000;
In my code cbRoutine is a call back function passed in as a parameter to call on successful connection.
The ECONNREFUSED error indicates that it can't connect to where the function is hosted (in this case localhost)
dbConnection.js
const mysql = require('mysql');
const connection = mysql.createPool({
connectionLimit: 10, // default = 10
host: '127.0.0.1',
user: 'root',
password: '',
database: 'dname'
});
module.exports = connection;

Why won't Sequelize/Tedious connect to a localhost database?

I've been building a NodeJS/React app which connects to an MS SQL Server database. It was working fine, I uploaded it to the Windows hosting and it was working fine connecting to the dev database on a third party hosting company using this config file.
const Sequelize = require('sequelize');
const config = {
user: "myusername",
password: "mypassword",
server: "database_server",
database: "mydatabase",
options: {
enableArithAbort: true
},
};
const seqInstance = new Sequelize(
//
config.database,
config.user,
config.password,
{
dialect: "mssql",
host: config.server,
dialectOptions: {
encrypt: true,
options: {
validateBulkLoadParameters: true
}
},
}
);
module.exports = { seqInstance };
But when I try to connect to the production database which is on the same server, localhost, using this change to the config -
const config = {
user: "mynewusername",
password: "mynewpassword",
server: "localhost",
database: "myproductiondatabase",
options: {
enableArithAbort: true
},
};
it refuses to connect and throws this error.
There are other app on the server connecting to that localhost sql server databases. Why is this small change not working?

How to connect AWS elasticache redis from Node.js application?

How to connect AWS elasticache redis from Node.js application ?
You're connecting to Redis. The fact that it's a managed AWS service is not really that important in this respect.
So, use a Node.js package that implements a Redis client interface, for example:
redis
node-redis
You can use the package ioredis
and stablish a connection like this
const Redis = require('ioredis')
const redis = new Redis({
port: 6379,
host: 'your-redis-host',
connectTimeout: 10000 // optional
});
You can try connecting using ioredis.
var Redis = require('ioredis');
var config = require("./config.json");
const redis = new Redis({
host: config.host,
port: config.port,
password: config.password, // If you have any.
tls: {}, // Add this empty tls field.
});
redis.on('connect', () => {
console.log('Redis client is initiating a connection to the server.');
});
redis.on('ready', () => {
console.log('Redis client successfully initiated connection to the server.');
});
redis.on('reconnecting', () => {
console.log('Redis client is trying to reconnect to the server...');
});
redis.on('error', (err) => console.log('Redis Client Error', err));
//check the functioning
redis.set("framework", "AngularJS", function(err, reply) {
console.log("redis.set ", reply);
});
redis.get("framework", function(err, reply) {
console.log("redis.get ", reply);
});

Issue connecting to my sql database using a REST api server with Node.js

I'm very new to coding servers and javascript in general but I'm currently trying to set up a REST api server and connect it to my sql database, for the moment I am doing everything locally. I am running ubuntu 18.04 while using NODE js. I have been able to successfully create a REST api and connect to it through an url of a webpage or with Postman. I have created a sql server database through my cmd terminal and have created test data on it. I've been looking at guides to connect the REST api to the database but I think the info I'm giving the api to connect is where my issue is occurring. I am starting with this below as my server.js where i have a folder Controller and a ProductController.js file where I'm handling the route /api/products .
var http = require('http');
var express = require('express');
var app = express();
var port = process.env.port || 3000;
var productController = require('./Controller/ProductController')();
app.use("/api/products", productController);
app.listen(port, function(){
var datetime = new Date();
var message = "Server running on Port:- " + port + " Started at :- " +
datetime;
console.log(message);
});
Below is my ProductController.js file. The issue might be here but I believe it is my next file called connect.js the table in my sql database is called 'data' hence the "SELECT * FROM data" part. when I try to GET this data in postman it displays the error i set up "Error while inserting data". so I believe when running I'm not getting data from sql so conn.close() is not being reached.
var express = require('express');
var router = express.Router();
var sql = require("mssql");
var conn = require("../connection/connect")();
var routes = function()
{
router.route('/')
.get(function(req, res)
{
conn.connect().then(function()
{
var sqlQuery = "SELECT * FROM data";
var req = new sql.Request(conn);
req.query(sqlQuery).then(function (recordset)
{
res.json(recordset.recordset);
conn.close();
})
.catch(function (err) {
conn.close();
res.status(400).send("Error while inserting data");
});
})
.catch(function (err) {
conn.close();
res.status(400).send("Error while inserting data");
});
});
return router;
};
module.exports = routes;
This is my connect.js file below. I have a password for root which is not *** but is correct on my machine. I have changed root's plug in to mysql_native_password in the mysql terminal. I think the server: part is wrong, I've tried commenting it out but still no connection. I do not have SQL Server Management Studio and have not found a way to get my sql server's name through the terminal. I've seen examples that seem to range of what info you need to give the api to connect. If someone has insight on that too that would be appreciated as well. My end goal is to eventually create GET and POST routes for the database and a function to manipulate the POST data but for now I'm just trying to get things connected so I can play around with the data being GET'ed. Thanks for any insight you can give, it is much appreciated.
var sql = require("mssql");
var connect = function()
{
var conn = new sql.ConnectionPool({
host: 'localhost'
user: 'root',
password: '********',
server: 'mysql',
database: 'test'
});
return conn;
};
Looks like you may have some errors in your connect.js file:
var conn = new sql.ConnectionPool({
host: 'localhost'
user: 'root',
password: '********',
server: 'mysql',
database: 'test'
});
should be in the format of:
const pool = new sql.ConnectionPool({
user: '...',
password: '...',
server: 'localhost',
database: '...'
})
Note that you currently have both host and server, looks like only server is needed. Also, server: 'mysql' doesn't make sense if you are connecting to a MSSQL database.
Source: node-mssql documentation
To diagnose the errors you should add some logging to your catch blocks:
.catch(function (err) {
console.log('connection error', err); //or Bunyan, Winston, Morgan, etc. logging library
conn.close();
let message = "Error while inserting data"
if (process.env.NODE_ENV === 'development') { //conditionally add error to result message
message += "\n"+err.toString());
}
res.status(500).send(message); //use 5xx for server problems, 4xx for things a user could potentially fix
});
And set NODE_ENV in your environment, for example in package.json:
"scripts": {
"start": "NODE_ENV=production node app.js"
"start-dev": "NODE_ENV=development node app.js"
}

Connecting to MSSQL server with Sequelize

Using the following tedious code, I can successfully connect to an Azure SQL Server.
const Connection = require('tedious').Connection;
const connection = new Connection({
userName: '[USER]',
password: '[PASSWORD]',
server: '[HOSTNAME]',
options: {encrypt: true}
});
connection.on('connect', (err) => {
if (err) {
console.log('error connecting', err);
} else {
console.log('connection successful');
}
});
However, using what should be the equivalent Sequelize code, I get a connection timeout error.
const Sequelize = require('sequelize');
const sequelize = new Sequelize('[DBNAME]', '[USER]', '[PASSWORD]', {
dialect: 'mssql',
host: '[HOSTNAME]',
dialectOptions: {
encrypt: true
}
});
sequelize.authenticate().then((err) => {
console.log('Connection successful', err);
})
.catch((err) => {
console.log('Unable to connect to database', err);
});
Any thoughts?
Using: sequelize 3.29.0, tedious 1.14.0, SQL Server v12
I was getting below error
SequelizeConnectionError: Server requires encryption, set 'encrypt' config option to true.
I tried it out with Azure SQL Database and below way is working for me.
const sequelize = new Sequelize('DB Name', 'Username', 'Password', {
host: 'Host',
dialect: 'mssql',
dialectOptions: {
options: {
encrypt: true,
}
}
});
If you're trying it out with Azure SQL Database, you might also want to specify a longer request timeout value:
[...]
dialectOptions: {
requestTimeout: 30000 // timeout = 30 seconds
}
[...]
I tried your Sequelize code and it works fine. So you might need to add Client IP address to allow access to Azure SQL Server. To do this, go to the Azure portal, click on All Resources, select your SQL server, click on Firewall in the SETTINGS menu.
Your client address is conveniently included in the list, so you can just click on Add client IP followed by Save. When you run your code now, it should connect.
if you are using sql server management studio then simply replace dialect:'mysql' with dialect:'mssql':
const sequelize = new Sequelize('DB Name', 'Username', 'Password', {
host: 'Host',
dialect: 'mssql',
dialectOptions: {
options: {
encrypt: true,
}
}
});

Categories