I have a problem with the connection to my database located in Azure, I was attempting to do a connection with a rest-API that I create, to a database that I have in Azure, this database I manage directly from SQL Server, and I can't make a connection with this.
I attempt to connect with another test database in SQL Server.
The rest-API ia create is in NodeJS
var sql = require('mssql');
var dbconfig = {
server:"Fernando\EQUIPO",
user: "<user>",
password: "<password>",
database: "<dbname>",
port: 1433,
option: {
encrypt: false
}
};
function getList() {
var record;
var conn = new sql.ConnectionPool(dbconfig);
conn.connect(function(err){
if(err) throw err;
var req = new sql.Request(conn);
req.query("select * from cliente", function(err, recordset) {
if(err) throw err;
else {
console.log(recordset);
record = recordset;
}
conn.close();
});
});
return record;
}
const { Router } = require('express');
const router = Router();
const _ = require('underscore');
const movies = require('../sample.json');
router.get('/', (req, res) => {
res.send(getList());
});
When I make a "get" to my local host http://localhost:3000/api/movies appears the following message in the console:
GET /api/movies 200 126.188 ms - -
(node:11868) UnhandledPromiseRejectionWarning: ConnectionError: Failed to connect to FernandoEQUIPO:1433 - getaddrinfo ENOTFOUND FernandoEQUIPO
at Connection.tedious.once.err (C:\Users\luisn\Desktop\rest-API\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:286:20)
at Connection.emit (events.js:198:13)
at Connection.socketError (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connection.js:1258:12)
at _connector.Connector.execute (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connection.js:1084:21)
at GetAddrInfoReqWrap._dns.default.lookup [as callback] (C:\Users\luisn\Desktop\rest-API\node_modules\tedious\lib\connector.js:152:16)
at GetAddrInfoReqWrap.onlookupall [as oncomplete] (dns.js:68:17)
(node:11868) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:11868) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
Connect to Azure SQL database:
Here's the example code connect to Azure SQL database with REST-API:
Note: the encrypt must be true.
You can get the server name from on Portal:
And you need to add the client IP address to the Azure SQL Server firewall settings:
Then you could connect to the Azure SQL database now. You can reference:Creating a Node.js REST API in Azure
Connect to SQL Server:
Your code is almost correct and need some change:
var sql = require('mssql');
var dbconfig = {
server:"localhost",
user: "<user>",
password: "<password>",
database: "<dbname>",
port: 1433,
option: {
encrypt: false
}
};
Like Abhishek Ranjan said, you should enter your server ip.
Hope this helps.
Welcome to StackOverflow.
ConnectionError: Failed to connect to FernandoEQUIPO:1433 - getaddrinfo ENOTFOUND FernandoEQUIPO
Your error states that it is unable to connect as it could not find a server at the given address.Make sure there is a server runninng and verify connection using some third party app.
Are you sure FernandoEQUIPO gets resolved to a proper hostname ?
Related
I am trying to fetch data from GCP cloud MySQL database using a cloud function. The cloud function is written in Nodejs. This function is making a query to fetch data from the database. I have created a Serverless VPC connector that I have attached to function and MySQL. MYSQL has private IP enabled. However I get the below error:
Error: connect ETIMEDOUT at
PoolConnection.Connection._handleConnectTimeout
(/workspace/node_modules/mysql/lib/Connection.js:409:13) at
Object.onceWrapper (events.js:519:28) at Socket.emit
(events.js:400:28) at Socket.emit (domain.js:537:15) at
Socket._onTimeout (net.js:495:8) at listOnTimeout
(internal/timers.js:557:17) at processTimers
(internal/timers.js:500:7) Error: connect ETIMEDOUT at
PoolConnection.Connection._handleConnectTimeout
(/workspace/node_modules/mysql/lib/Connection.js:409:13) at
Object.onceWrapper (events.js:519:28) at Socket.emit
(events.js:400:28) at Socket.emit (domain.js:537:15) at
Socket._onTimeout (net.js:495:8) at listOnTimeout
(internal/timers.js:557:17) at processTimers
(internal/timers.js:500:7)
Below is my Cloud function code:
const mysql = require('mysql');
const mysqlConfig = {
connectionLimit: 1,
host: '10.217.208.5',
port: '3306',
user: 'root',
password: 'tmc',
database: 'tmc'
};
let mysqlPool;
exports.helloWorld = (req, res) => {
mysqlPool = mysql.createPool(mysqlConfig);
mysqlPool.query(`SELECT * FROM tmc`, function (error, results) {
console.log(error);
console.log(results)
res.status(200).send(results);
});
};
My Cloud SQL instance
Network for private connections:
GCP function VPC connector
In my case it was a firewall issue. I allowed a particular IP and things worked. If u face a similar issue you may also try allowing 0.0.0.0/0 (Just for testing) inside SQL connections settings. 0.0.0.0/0 opens SQL to the world
I've checked around Stack and the Mongoose docs for this, but I can't seem to get it right. As implied in the title everything was fine until i upgraded the packages for mongoose and connect-mongo.
Here's my database.js:
var mongoose = require('mongoose');
var mongodbUri = require('mongodb-uri');
function encodeMongoURI (urlString) {
if (urlString) {
var parsed = mongodbUri.parse(urlString)
urlString = mongodbUri.format(parsed);
}
return urlString;
}
mongoose.connect(encodeMongoURI(process.env.MONGODB_URI) || 'mongodb://localhost:27017/goGradesDB',//specifies goGradesDB as the db to use locally
{
useNewUrlParser: true,
useUnifiedTopology: true,
useFindAndModify: false,
useCreateIndex: true,
}).catch(error => handleError(error));
var db = mongoose.connection;
db.on('error', console.error.bind(console, 'MongoDB connection error:'));
module.exports = db;
After looking over the docs in mongoose and searching this site I've tried the following:
installed the mongodb-uri package to parse the uri (although I'm not sure if that's needed for the local db. I can't get onto my heroku db either, but that's something I'm working with support on.
added the "useNewURLParser", etc. tag.
added the port number into the local db address
added the catch onto the end of mongoose.connect
Despite this I keep getting the following error output in my terminal and the db times out whenever I try to login to the app. Here's the output:
"The server is running on port 3000!
(node:71951) UnhandledPromiseRejectionWarning: MongoParseError: URI malformed, cannot be parsed"
and later,
"(node:71951) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 2)
(node:71951) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code."
Any insight would be much appreciated. Thank you!
I'm trying to make a query on my local MySQL database, but when I use the knex it says for me to install the driver of sqlite3 which I don't need because my database is a MySQL.
I tried to install the drive of sqlite3 just to see if it would fix my problem but it just made other errors related to sqlite3 show up, so I just removed the sqlite3 driver.
I already have the driver of MySQL. Below is my code.
Why this error is happening? From what I know it shouldn't be asking me for a sqlite3 driver but just the MySQL as I passed in the configuration for knex.
*** I had already tried to use the driver mysql2 and nothing changed...
const knex = require('knex');
require('dotenv').config();
const listUsers = async (req, res) => {
console.log(process.env.DATABASE_PASSWORD);
//res.send(process.env.DATABASE_USER);
knex({
client: 'mysql',
connection: {
host: process.env.DATABASE_HOST,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD,
database: process.env.DATABASE_NAME
}
})
knex('users')
.select('*')
.then(mysqlres => res.send(mysqlres))
.catch(mysqlerr => res.send(console.log(mysqlerr)))
}
module.exports = {
listUsers
};
and this is my error :
Knex: run
$ npm install sqlite3 --save
Cannot find module 'sqlite3'
Require stack:
- D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\dialects\sqlite3\index.js
- D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\knex.js
- D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\index.js
- D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\knex.js
- D:\coding\Studies\Moblex\backend-mysql\src\controllers\userController.js
- D:\coding\Studies\Moblex\backend-mysql\src\routes.js
- D:\coding\Studies\Moblex\backend-mysql\src\server.js
Error: Cannot find module 'sqlite3'
Require stack:
- D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\dialects\sqlite3\index.js
- D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\knex.js
- D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\index.js
- D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\knex.js
- D:\coding\Studies\Moblex\backend-mysql\src\controllers\userController.js
- D:\coding\Studies\Moblex\backend-mysql\src\routes.js
- D:\coding\Studies\Moblex\backend-mysql\src\server.js
at Function.Module._resolveFilename (internal/modules/cjs/loader.js:965:15)
at Function.Module._load (internal/modules/cjs/loader.js:841:27)
at Module.require (internal/modules/cjs/loader.js:1025:19)
at require (internal/modules/cjs/helpers.js:72:18)
at Client_SQLite3._driver (D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\dialects\sqlite3\index.js:36:12)
at Client_SQLite3.initializeDriver (D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\client.js:232:26)
at Client_SQLite3.Client (D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\client.js:70:10)
at new Client_SQLite3 (D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\dialects\sqlite3\index.js:18:10)
at new Knex (D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\knex.js:53:28)
at Knex (D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\knex.js:17:12)
(node:12648) UnhandledPromiseRejectionWarning: Error: Knex: run
$ npm install sqlite3 --save
Cannot find module 'sqlite3'
Require stack:
- D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\dialects\sqlite3\index.js
- D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\knex.js
- D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\index.js
- D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\knex.js
- D:\coding\Studies\Moblex\backend-mysql\src\controllers\userController.js
- D:\coding\Studies\Moblex\backend-mysql\src\routes.js
- D:\coding\Studies\Moblex\backend-mysql\src\server.js
at Client_SQLite3.initializeDriver (D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\client.js:236:13)
at Client_SQLite3.Client (D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\client.js:70:10)
at new Client_SQLite3 (D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\dialects\sqlite3\index.js:18:10)
at new Knex (D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\knex.js:53:28)
at Knex (D:\coding\Studies\Moblex\backend-mysql\node_modules\knex\lib\knex.js:17:12)
at listUsers (D:\coding\Studies\Moblex\backend-mysql\src\controllers\userController.js:19:5)
at Layer.handle [as handle_request] (D:\coding\Studies\Moblex\backend-mysql\node_modules\express\lib\router\layer.js:95:5)
at next (D:\coding\Studies\Moblex\backend-mysql\node_modules\express\lib\router\route.js:137:13)
at Route.dispatch (D:\coding\Studies\Moblex\backend-mysql\node_modules\express\lib\router\route.js:112:3)
at Layer.handle [as handle_request] (D:\coding\Studies\Moblex\backend-mysql\node_modules\express\lib\router\layer.js:95:5)
(node:12648) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). To terminate the node process on unhandled promise rejection, use the CLI flag `--unhandled-rejections=strict` (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1)
(node:12648) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
So guys i just figured that i need to make a new instance of Knex when i apply the configuration and that will work ! And the reason that it was asking for the drive sqlite3 before is because knex uses the sqlite3 model. So because i was not making a new instance of the Knex with my own configuration it was using it's default.
so this is my code for the sollution !
const listUsers = async (req, res) => {
const knexapp = knex({
client: 'mysql2',
connection: {
database: process.env.DATABASE_NAME,
user: process.env.DATABASE_USER,
password: process.env.DATABASE_PASSWORD
},
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'knex_migrations'
}
})
knexapp('users').select('*').then(resmsql => res.send(resmsql)).catch(err => res.send(err))
I am trying to run the below program to create a mongo database using Node.js by running node app.js.
app.js
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://hostname:27017/mydb";
MongoClient.connect(url, function(err, db) {
if (err) throw err;
console.log("Database created!");
db.close();
});
Below is the error I'm getting :-
(node:20815) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
MongoNetworkError: failed to connect to server [hostname_fqdn:27017] on first connect [Error: connect ECONNREFUSED 10.127.45.59:27017
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1134:16) {
name: 'MongoNetworkError'
}]
at Pool.<anonymous> (/root/myfolder/node_modules/mongodb/lib/core/topologies/server.js:438:11)
at Pool.emit (events.js:223:5)
at /root/myfolder/node_modules/mongodb/lib/core/connection/pool.js:562:14
at /root/myfolder/node_modules/mongodb/lib/core/connection/pool.js:995:11
at /root/myfolder/node_modules/mongodb/lib/core/connection/connect.js:32:7
at callback (/root/myfolder/node_modules/mongodb/lib/core/connection/connect.js:280:5)
at Socket.<anonymous> (/root/myfolder/node_modules/mongodb/lib/core/connection/connect.js:310:7)
at Object.onceWrapper (events.js:313:26)
at Socket.emit (events.js:223:5)
at emitErrorNT (internal/streams/destroy.js:92:8) {
name: 'MongoNetworkError'
}
The file/node_modules/package.json all are located in a CentOS Virtual Machine.
You need to start the MongoDB Service after installing.
Edited:
If you have already started service and connecting mongo via terminal, then try to remove mongo lock file (rm /var/lib/mongodb/mongod.lock) and repair mongod (mongod -–repair). Now start mongo service and see if you can connect. I had similar issue with EC2 and Compass and tried above to resolve.
My Node.js app is able to work with local Postgres database via npm pg module.
I can connect to the Heroku hosted Postgres database (free Hobby Dev plan) via command line with heroku pg:psql command as well.
But when my Node.js app is trying to query to Heroku hosted Postgres database I am receiving an self signed certificate error.
Here is the output with self signed certificate error:
(node:2100) UnhandledPromiseRejectionWarning: Error: self signed certificate
at TLSSocket.onConnectSecure (_tls_wrap.js:1051:34)
at TLSSocket.emit (events.js:189:13)
at TLSSocket._finishInit (_tls_wrap.js:633:8)
(node:2100) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:2100) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
D:\MY\DEV\PROJECTS\AdsSubscribeBot\test.js:57
if (err) throw err;
^
Error: Connection terminated unexpectedly
at Connection.con.once (D:\MY\DEV\PROJECTS\AdsSubscribeBot\node_modules\pg\lib\client.js:264:9)
at Object.onceWrapper (events.js:277:13)
at Connection.emit (events.js:189:13)
at Socket.<anonymous> (D:\MY\DEV\PROJECTS\AdsSubscribeBot\node_modules\pg\lib\connection.js:76:10)
at Socket.emit (events.js:194:15)
at TCP._handle.close (net.js:597:12)
Simpliest way to reproduce this error is to try use the sample code to connecting in Node.js from Heroku devcenter:
https://devcenter.heroku.com/articles/heroku-postgresql#connecting-in-node-js
Here is the sample of the code that causes self signed certificate error:
const connectionString = 'postgres://USERNAME:PASSWORD#HOST:PORT/DB_NAME';
const { Client } = require('pg');
const client = new Client({
connectionString: connectionString,
ssl: true
});
client.connect();
client.query('SELECT * FROM users;', (err, res) => {
if (err) throw err;
for (let row of res.rows) {
console.log(JSON.stringify(row));
}
client.end();
});
Maybe someone has faced the same issue and know the way how to solve it.
Thanks in advance for any help.
Check you pg config. It sounds like you are using pg 8 which deprecates
implicit disabling of certificate verification (as you have in your config where ssl is set to true but no ssl configuration is provided). Specify rejectUnauthorized: true to require a valid CA or rejectUnauthorized: false to explicitly opt out of MITM protection.
You can do so where you set up your pg config as follows
const client = new Client({
connectionString: connectionString,
ssl: { rejectUnauthorized: false }
})
If anyone is still seeing issues with this after appending the SSL object to the Client object and they are using a connection string. Make sure that you don't have an ssl parameter in the connection string. If you are working with Digital Ocean this parameter is included in the generated connection string.
This is how Digital Ocean formats their connection strings by default
postgres://USERNAME:PASSWORD#HOST:PORT/DB_NAME:25060/defaultdb?&sslmode=require
To get this to work, I had to add:
ssl: { rejectUnauthorized: false }
but also add this to the environment:
NODE_TLS_REJECT_UNAUTHORIZED=0
Below is a variation of the accepted answer using Knex.js. Tested on Heroku.
const parse = require('pg-connection-string').parse;
const pgconfig = parse('your-pg-connection-string');
pgconfig.ssl = { rejectUnauthorized: false };
const knex = Knex({
client: 'pg',
connection: pgconfig,
});
Thanks to #samkhan27. I just added ssl: { rejectUnauthorized: false }
My full code:
const db = new Sequelize(
process.env.DATABASE_URL ||
`postgres://postgres:w2w2#localhost:5432/${databaseName}`,
{
logging: false,
ssl: { rejectUnauthorized: false } //solved the problem with self signed sertificate
}
)