Cannot Connect to SQL Server after hosting the app on heroku - javascript

I'm using mssql along with node.
I call a function to connect to the database:
const sql = require('mssql')
async () => {
try {
const pool = await sql.connect(`mssql://${process.env.DATAUSER}:${process.env.DATAPASS}#${process.env.SERVER}`)
} catch(err) {
console.log(err)
}
}
This works perfectly fine when i'm on a localhost but after i've hosted it to heroku and add the env variables. The error I get is (I changed the ip address to 5's):
ConnectionError: Failed to connect to 55.5.5.555:1433 in 15000ms
My process.env.SERVER = 55.5.5.555/SpecificDatabase and If that means anything

I don't see any reference to your specific database or schema in this code. It may be possible that your local implementation of the data server differs from the heroku implementation in respect to the default schema or database to which a user is directed. Therefore, you may need to add a database or schema field to your connection call.
For example, my pool code to connect to the OSU server is:
var mysql = require('mysql');
var pool = mysql.createPool({
connectionLimit : 10,
host : 'classmysql.engr.oregonstate.edu',
user : 'username',
password : 'password',
database : 'database_name',
multipleStatements: true
});
module.exports.pool = pool;
Though my implementation here was with mysql and not mssql, it may hold true that you need to explicitly name a specific database or schema.

Related

Mongoose.connect() fails when database is specified in connection string

I'm running a local MongoDB server and am trying to connect to it from a node.js server using the Mongoose library.
I'm using SCRAM-SHA-1 as the authentication mechanism
I'm able to connect to it with the admin account when I don't specify a database to connect to, using a connection string such as:
mongodb://{username}:{password}#{address}:{port}?authMechanism=SCRAM-SHA-256
But when I try to specify which database to connect to, using a connection string such as:
mongodb://{username}:{password}#{address}:{port}/database123?authMechanism=SCRAM-SHA-256
the authentication fails.
For reference, my code looks like:
const mongoose = require('mongoose');
let conn_string = `mongodb://mongo_uname:mongo_pass#192.168.1.1:3000/database123?authMechanism=SCRAM-SHA-256`
mongoose
.connect(database_uri, {
useUnifiedTopology: true
})
.then(() => console.log('MongoDB database Connected...'))
.catch((err) => console.log(err))
Is there a different way to specify which database to connect to with mongoose, or is there something I can do differently when constructing the connection string to make it work?
Cheers.
Make sure that the database user you are using is configured to read and write to the database uou are trying to connect to.
import mongoose from "mongoose";
const mongoDB = "mongodb://localhost:27017/twlight";
mongoose.Promise = global.Promise;
mongoose.connect(mongoDB, { useNewUrlParser: true })
.then(() => {
console.log("Database is connected");
},
(err) => {
console.log("There is problem while connecting database " + err);
});
Please try
Note: twilight is database name
If you are using Mongoose v6+, you should NOT specify useUnifiedTopology.
That is deprecated and if you include it, Mongoose will throw the error. Try to include the connection string only:
mongoose.connect(database_uri)
My error ended up being in the configuration of the database user I was trying to connect with, they weren't even set up to read or write to the database I was attempting to connect to.

Error Continue wait issue on Cube.js backend

I'm having some trouble connecting to the cube.js backend on AWS serverless and executing the /cubejs-api/v1/load request in the frontend dashboard. I keep getting {"error":"Continue wait"} instead of a result returned.
I am following the react-dashboard guide for authentication but deployed using the backend cube.js serverless AWS template.
This is what my main cube.js file looks like.:
const AWSHandlers = require('#cubejs-backend/serverless-aws');
const PostgresDriver = require('#cubejs-backend/postgres-driver');
const fs = require("fs");
const jwt = require("jsonwebtoken");
const jwkToPem = require("jwk-to-pem");
const jwks = JSON.parse(fs.readFileSync("jwks.json"));
const _ = require("lodash");
module.exports = new AWSHandlers({
checkAuth: async (req, auth) => {
const decoded = jwt.decode(auth, { complete: true });
const jwk = _.find(jwks.keys, x => x.kid === decoded.header.kid);
const pem = jwkToPem(jwk);
req.authInfo = jwt.verify(auth, pem);
},
externalDbType: 'postgres',
externalDriverFactory: () => new PostgresDriver({
host: process.env.CUBEJS_EXT_DB_HOST,
database: process.env.CUBEJS_EXT_DB_NAME,
port: process.env.CUBEJS_EXT_DB_PORT,
user: process.env.CUBEJS_EXT_DB_USER,
password: process.env.CUBEJS_EXT_DB_PASS,
})
});
I didn't have the redis URL set correctly initially and fixed the connection to redis after adding redis:// extension before the url to the serverless.yml file to fix that so I know it's not redis connection issue. I'm assuming there's some other problem.
The cubejs process function has no logs at all. I have setup a NAT gateway and subnets according to the guide on the deployment site so that i have 1 subnet for each zone just for the lambda and they have been added to the new NAT gateway that was created and to the 2 functions so they have internet access.
What could be the issue? Did I configure something wrong or do I need to make changes to something?
#cubejs-backend/serverless uses internet connection to access messaging API as well as Redis inside VPC for managing queue and cache.
Such continuous Continue wait messages usually mean that there's a problem with internet connection or with Redis connection. If it's Redis you'll usually see timeouts after 5 minutes or so in both cubejs and cubejsProcess functions. If it's internet connection you will never see any logs of query processing in cubejsProcess function.

How to render rows of data in React.js from mysql database using Express.js?

Can someone explain or point to some tutorial where is explained how to render rows of data from mySql database into react.js component?
I've made small database using mysql workbench and this baza.js file inside my project folder:
var mysql = require('mysql');
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'db'
});
connection.connect(function(err) {
if (err) throw err;
connection.query("SELECT * FROM promjer", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});
When I run node baza.js in my CMD, everything seems fine, I get everything from that specific table inside CMD terminal so I guess my database is ok and it's connected with app.
What troubles me is how to render that data inside my app?
I know that React by itself can't handle data so i should use Express.js. But I don't get what to do with it. Express should be running on other port so how should I even get data to component in app which is running on port 3000 if express is running on port 9000?
Thanks in advance!

How to connect to remote mysql database using Node.js

I'm trying to connect to a mysql database using node. It is working perfectly fine when connecting with localhost.
var pool = mysql.createPool({
connectionLimit : 100,
host : 'http://<ip-address here>/phpmyadmin',
user : '*********',
password : '*********',
database : '*********'
});
pool.getConnection(function(err, connection) {
// Use the connection
connection.query( 'SELECT * FROM table', function(err, rows) {
// And done with the connection.
connection.release();
// Don't use the connection here, it has been returned to the pool.
});
});
The above code is not working.
I haven't found any answer on Google as well as here.
Host is only contains IP address, try to remove phpmyadmin.

Cannot connect to SQL Server with Node.js and Tedious

When I try to use Node.js and Tedioius to connect to a local SQL Server instance I get this error:
{ [ConnectionError: Failed to connect to XXXXX:1433 - connect ECONNREFUSED]
name: 'ConnectionError',
message: 'Failed to connect to XXXXX:1433 - connect ECONNREFUSED',
code: 'ESOCKET' }
Here is my connection object:
var config = {
userName: 'username',
password: 'password',
server: 'XXXXX',
options: {
database: 'databasename',
instancename: 'SQLEXPRESS'
}
};
I have checked and TCP/IP is enabled and broadcasting on port 1443 according to Configuration Manager. The SQL Server Browser service is also running, which I read may be causing this type of issue if not. I have disabled my antivirus and firewall and that hasn't helped either.
Any insight?
So what I am guessing happens is that even though Tedious lets you include instance name in 'options' it either doesn't use it or can't use it as it needs to be used. After doing some research, what should be happening is when you give SQL Server the instance name, it redirects you from port 1433 to the dynamic port it is using for that instance. I didn't know it was using a dynamic port, but if your instance is named the port will always be dynamic. I don't know where I saw it broadcasting on 1433, that was my mistake.
To check the dynamic port, look here:
From this information, I changed my code to this:
var config = {
userName: 'username',
password: 'password',
server: 'XXXXX',
options: {
port: 49175,
database: 'databasename',
instancename: 'SQLEXPRESS'
}
};
All is good now, hope this helps someone.
If anyone else is new to SQL Server like I am, and is dealing with this issue, once you enable TCP/IP in SQL Server Config Manager by following these steps:
> SQL Server Network Config
> Protocols for YOURSQLSERVERINSTANCE
> TCP/IP
> Enable
you get a warning message that looks like this:
Any changes made will be saved; however, they will not take effect until the service is stopped and restarted.
I took this to mean, disconnect from the database service in SQL Server Management Studio and reconnect, but this needs to happen in SQL Server Config Manager under the SQL Server Services tab. Find you SQL Server instance, stop and restart it, and hopefully you will be golden! This worked like a charm for me. Oddly, enabling the Named Pipes protocol seemed to work without a restart (I could see the difference in the error message), so I thought for sure it had stopped and restarted as needed.
Also, be sure to enable SQL Server Browser services as well. This and enabling TCP/IP and restarting the service were the keys for me.
If you still have problems after enabling TCP/IP protocol, I would suggest you check that SQL Server Browser Service is running. In my case I spent a lot of time till I realised it wasn't running.
This configuration run fine for me:
var config = {
user: 'user',
password: 'userPwd',
server: 'localhost',
database: 'myDatabase',
options: {
truestedConnection: true,
instanceName: 'SQLEXPRESS'
}
If you still got this error,
"...'Failed to connect to Server:1433 - connect ECONNREFUSED Server IP:1433',
code: 'ESOCKET' }"
and you've checked all the following:
Enable TCP/IP
Open Port 1433
Config setup correctly (database, server, username and password}
No Dynamic ports configured
Check your SQL server version. In my case, I discovered that I could connect to SQL 2012, but not SQL server 2016 with the same code. It appears SQL Server 2016 is not supported by the tedious driver yet.
...
You have to enabled tcp/ip on protocol for MSSQLSERVER
and activate both authentication
here is the complete code
const {
Request
} = require('tedious');
var Connection = require('tedious').Connection;
var config = {
server: 'DESKTOP-RU9C12L', //update me
authentication: {
type: 'default',
options: {
userName: 'begaak', //update me
password: 'begaak#123', //update me
}
},
options: {
encrypt: true,
enableArithAbort: true,
integratedSecurity: true,
trustServerCertificate: true,
rowCollectionOnDone: true,
database: 'selvapoc' //update me
}
};
var connection = new Connection(config);
connection.connect(function(err) {
console.log('testing')
// var request = new Request("Select * from products", function(err, rowCount, rows) {
// console.log(rowCount);
// console.log(JSON.stringify(rows))
// });
// connection.execSql(request);
connection.execSql(new Request('SELECT * FROM Products', function(err, rowCount, rows) {
if (err) {
throw err;
}
})
.on('doneInProc', function(rowCount, more, rows) {
console.log(more, rows[0], rowCount); // not empty
}));
});
connection.on('connect', function(err) {
// If no error, then good to proceed.
if (err) console.log(err)
console.log("Connected");
});
before starting the code configure these with SQL SERVER CONFIGURATION MANAGER

Categories