How to connect remote database via NodeJS - javascript

I am trying to connect to Heroku's database via NodeJs.
I tried to connect to localhost and it worked perfectly. But when i tried to remote database it gives error.
Here is the localhost connection code which is working perfectly.
const conectionString='postgressql://postgres:1234#localhost:5433/Qfield'
const client= new Client({
connectionString:conectionString
})
client.connect()
//client.query('select * from point',(err,res)=>{
// console.log(err,res)
// client.end()
//})
client.query('SELECT * FROM trees', function(err, res) {
console.log(err,res)
client.end()
});
Here is the error connection which is remote database.
const {Pool,Client}=require('pg')
const conectionString='postgressql://Username:Password#ec2-54-228-243-29.eu-west-1.compute.amazonaws.com:5432/database'
const client= new Client({
connectionString:conectionString
})
client.connect()
//client.query('select * from point',(err,res)=>{
// console.log(err,res)
// client.end()
//})
client.query('SELECT * FROM trees', function(err, res) {
console.log(err,res)
client.end()
});
Here is the error.
(node:14896) UnhandledPromiseRejectionWarning: error: no pg_hba.conf entry for host "193.140.225.88", user "vfoiltyjszbpav", database "dduigib0uc8ebt", SSL off
at Connection.parseE (C:\Users\CBS Lab\Desktop\postgres_conn\node_modules\pg\lib\connection.js:604:11)
at Connection.parseMessage (C:\Users\CBS Lab\Desktop\postgres_conn\node_modules\pg\lib\connection.js:401:19)
at Socket.<anonymous> (C:\Users\CBS Lab\Desktop\postgres_conn\node_modules\pg\lib\connection.js:121:22)
at Socket.emit (events.js:198:13)
at addChunk (_stream_readable.js:288:12)
at readableAddChunk (_stream_readable.js:269:11)
at Socket.Readable.push (_stream_readable.js:224:10)
at TCP.onStreamRead [as onread] (internal/stream_base_commons.js:94:17)
(node:14896) 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:14896) [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.
Error: Connection terminated unexpectedly
at Connection.con.once (C:\Users\CBS Lab\Desktop\postgres_conn\node_modules\pg\lib\client.js:252:9)
at Object.onceWrapper (events.js:286:20)
at Connection.emit (events.js:198:13)
at Socket.<anonymous> (C:\Users\CBS Lab\Desktop\postgres_conn\node_modules\pg\lib\connection.js:131:10)
at Socket.emit (events.js:203:15)
at endReadableNT (_stream_readable.js:1145:12)
at process._tickCallback (internal/process/next_tick.js:63:19)
How can I fix this error? What am I doing wrong?

Add ssl=true to your connection string to fix the error you've got:
const conectionString='postgressql://Username:Password#ec2-54-228-243-29.eu-west-1.compute.amazonaws.com:5432/database?ssl=true'

Related

How do I catch an ECONNRESET error using the basic FTP-Library?

I want my program to continue running after catching ECONNRESET. How do I do that? I'm using basic-ftp for my ftp library. Here's the error below:
Node.js v17.7.2
node:events:505
throw er; // Unhandled 'error' event
^
Error: read ECONNRESET
at TCP.onStreamRead (node:internal/stream_base_commons:217:20)
Emitted 'error' event on Socket instance at:
at emitErrorNT (node:internal/streams/destroy:164:8)
at emitErrorCloseNT (node:internal/streams/destroy:129:3)
at processTicksAndRejections (node:internal/process/task_queues:83:21) {
errno: -4077,
code: 'ECONNRESET',
syscall: 'read'
}
How do I catch it and have the program continue running? I've already tried try/catch blocks shown below:
async connect(port,ip_address){
try{
await this.client.access({
port: port,
host: ip_address,
secure: false
})
}
catch{
this.num_of_files_read=0;
this.files_completed=0;
return 1
}
return 0
}

(node:42790) UnhandledPromiseRejectionWarning: Error: socket hang up

I am trying to send POST request from a NodeJs script to Python server (running with flask and waitress).
Most of the times the request is failed with the below error.
(node:42790) UnhandledPromiseRejectionWarning: Error: socket hang up
at connResetException (internal/errors.js:639:14)
at TLSSocket.socketOnEnd (_http_client.js:499:23)
at TLSSocket.emit (events.js:412:35)
at endReadableNT (internal/streams/readable.js:1334:12)
at processTicksAndRejections (internal/process/task_queues.js:82:21)
(Use `node --trace-warnings ...` to show where the warning was created)
(node:42790) 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: 2)
(node:42790) [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.
I am using NodeJs with axios package to send the request, and the configuration is as given below:
let axiosClient = axios.create({
timeOut: 300000,
maxContentLength: Infinity,
maxBodyLength: Infinity,
httpsAgent: new https.Agent({ keepAlive: true }),
httpAgent: new http.Agent({ keepAlive: true }),
});
let response = await axiosClient.post(end_point_url, data);
And when I checked in the server I could see that the 200 response is being sent, however in the client it is throwing an error.
My expectation is it should be successful in the first try, hence catching the error and retrying may not help in my case as most of the times it fails anyways.
Could you please guide in finding the root cause and fixing the same.
Thank you
let response = await axiosClient.post(end_point_url, data);
You should check end points correctly and use it in try and catch block

MongoDB (Mongoose) with Node.js connection errors - Looking for insight

I am new to node.js and mongoDB Atlas. I am having an issue connecting to Mongo Atlas using the Node.js version 3.0 or later connection string.
const MongoDB = 'mongodb+srv://<user>:<password>#cluster0-nnezr.mongodb.net/<dbname>?retryWrites=true&w=majority'
When I use this connection string I get the following error -
MongoDB connection error: Error: querySrv ETIMEOUT _mongodb._tcp.cluster0-nnezr.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19) {
errno: undefined,
code: 'ETIMEOUT',
syscall: 'querySrv',
hostname: '_mongodb._tcp.cluster0-nnezr.mongodb.net'
}
(node:38809) UnhandledPromiseRejectionWarning: Error: querySrv ETIMEOUT _mongodb._tcp.cluster0-nnezr.mongodb.net
at QueryReqWrap.onresolve [as oncomplete] (dns.js:203:19)
(Use node --trace-warnings ... to show where the warning was created)
(node:38809) UnhandledPromiseRejectionWarning: Unhandled promise rejection. This error originated either by throwing inside ofan 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:38809) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections thatare not handled will terminate the Node.js process with a non-zero exit code.
I have found a workaround using the previous connection string for node.js version 2.2.12 -
mongodb://<user>:<password>#cluster0-shard-00-00-nnezr.mongodb.net:27017,cluster0-shard-00-01-nnezr.mongodb.net:27017,cluster0-shard-00-02-nnezr.mongodb.net:27017/<dbname>?ssl=true&replicaSet=Cluster0-shard-0&authSource=admin&retryWrites=true&w=majority
When connecting I have to add {useUnifiedTopology: true}
mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true });
Can anyone give me a little insight on what im doing wrong with the new connection string?
Thanks!
have write user, password and maybe also database ,
const MongoDB = 'mongodb+srv://<user>:<password>#cluster0-nnezr.mongodb.net/<dbname>?retryWrites=true&w=majority'
user = your mongodb user name
password = your mongodb password
dbname = Database name
and don't forget to create a new user in MongoDB atlas.

NestJS and Express causing intermittent UnhandledPromiseRejectionWarning

I cannot for the life of me cannot figure this out. It happens once every so often doesn't cause any issues with the application itself but i have no idea what is causing this. Im making simultaneous calls to the api from the browser if that has anything to do with it.
[Nest] 16608 - 11/7/2018, 1:23:08 PM [NestApplication] Nest application successfully started
[Nest] 16608 - 11/7/2018, 1:23:23 PM [LoggerMiddleware] Request /api/observation-statement/pending-count +14943ms
[Nest] 16608 - 11/7/2018, 1:23:23 PM [LoggerMiddleware] Request /api/observation-statement/revision-count +16ms
(node:14968) UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client
at ServerResponse.setHeader (_http_outgoing.js:469:11)
at ServerResponse.header (C:\Users\Ricardo Saracino\IdeaProjects\sor-api\node_modules\express\lib\response.js:767:10)
at ServerResponse.send (C:\Users\Ricardo Saracino\IdeaProjects\sor-api\node_modules\express\lib\response.js:170:12)
at ServerResponse.json (C:\Users\Ricardo Saracino\IdeaProjects\sor-api\node_modules\express\lib\response.js:267:15)
at ExpressAdapter.reply (C:\Users\Ricardo Saracino\IdeaProjects\sor-api\node_modules\#nestjs\core\adapters\express-adapter.js:44:52)
at ExceptionsHandler.catch (C:\Users\Ricardo Saracino\IdeaProjects\sor-api\node_modules\#nestjs\core\exceptions\base-exception-filter.js:16:33)
at ExceptionsHandler.next (C:\Users\Ricardo Saracino\IdeaProjects\sor-api\node_modules\#nestjs\core\exceptions\exceptions-handler.js:15:20)
at C:\Users\Ricardo Saracino\IdeaProjects\sor-api\node_modules\#nestjs\core\router\router-proxy.js:23:35
at Layer.handle_error (C:\Users\Ricardo Saracino\IdeaProjects\sor-api\node_modules\express\lib\router\layer.js:71:5)
at trim_prefix (C:\Users\Ricardo Saracino\IdeaProjects\sor-api\node_modules\express\lib\router\index.js:315:13)
(node:14968) 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:14968) [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.
I've reduced the calls to a pretty simple function, and make sure the call is returning a unique value (i thought it might be a 304 issue)
#Get('revision-count')
async countRevisions(#User() user, #Param() params) {
user.count ++;
return {
status: 'success',
data: {
rand: user.count,
}
};
}
this was happening prior to the middleware

Connect Sails JS to SQL Server EXPRESS

I'm learning Sails JS (and NodeJS), and I'm trying to set a connection to SQL Server Express. What I have so far:
A database called test-project-db with a table inside called TestTable1. It has two columns: name varchar(20) and description varchar(100).
A sails project generated with sails new, and a model/component made with sails generate api TestTable1.
My files:
- api/models/TestTable1.js
module.exports = {
attributes: {
name: {
type: 'string',
},
description: {
type: 'string',
},
}
};
- config/connections.js:
sqlserver: {
adapter : 'sails-sqlserver',
user : 'sa',
password: 'passw',
host : 'localhost\\SQLEXPRESS',
database: 'test-project-db'
}
- config/models.js:
module.exports.models = {
connection: 'sqlserver',
migrate: 'safe',
};
But when I run the server with sails lift and go to localhost:1337/testtable1, I get the error:
(node:15756) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): ConnectionError: Failed to connect to localhost:undefined in 60000ms
(node:15756) [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.
And, if instead of sails-sqlserver I use sails-mssqlserver, I get (in the console):
{"name":"Sails-MSSqlserver","hostname":"DESKTOP-PMN0K03","pid":15928,"level":30,"msg":"Error in __FIND__: { ConnectionError: Failed to connect to localhost:undefined in 60000ms\n at Connection.<anonymous> (D:\\Práctica 2\\test-project\\node_modules\\sails-mssqlserver\\node_modules\\mssql\\lib\\tedious.js:378:25)\n at Object.onceWrapper (events.js:315:30)\n at emitOne (events.js:116:13)\n at Connection.emit (events.js:211:7)\n at Connection.connectTimeout
(D:\\Práctica 2\\test-project\\node_modules\\sails-mssqlserver\\node_modules\\tedious\\lib\\connection.js:467:12)\n at ontimeout (timers.js:475:11)\n at tryOnTimeout (timers.js:310:5)\n at Timer.listOnTimeout (timers.js:270:5)\n name: 'ConnectionError',\n message: 'Failed to connect to localhost:undefined in 60000ms',\n code: 'ETIMEOUT' }","time":"2018-01-31T19:00:27.325Z","v":0}
error: Sending 500 ("Server Error") response:
Error (E_UNKNOWN) :: Encountered an unexpected error
ConnectionError: Failed to connect to localhost:undefined in 60000ms
at Connection.<anonymous> (D:\Práctica 2\test-project\node_modules\sails-mssqlserver\node_modules\mssql\lib\tedious.js:378:25)
at Object.onceWrapper (events.js:315:30)
at emitOne (events.js:116:13)
at Connection.emit (events.js:211:7)
at Connection.connectTimeout (D:\Práctica 2\test-project\node_modules\sails-mssqlserver\node_modules\tedious\lib\connection.js:467:12)
at ontimeout (timers.js:475:11)
at tryOnTimeout (timers.js:310:5)
at Timer.listOnTimeout (timers.js:270:5)
Details: ConnectionError: Failed to connect to localhost:undefined in 60000ms
And in the browser:
[Error (E_UNKNOWN) Encountered an unexpected error] Details: ConnectionError: Failed to connect to localhost:undefined in 60000ms
Along a 500 error page.
Any idea on what am I doing wrong?
localhost:undefined --> The port is undefined because you didn't provide it in the configuration. Add in the port attribute into your sqlserver connection within config/connections.js, and assign it your database server's port.
Side note: learning Sails while learning Node is quite a handful, especially since Sails can look intimidating at first. Just take it piece by piece, and you'll definitely get a hang of it. If you're familiar with MVC frameworks, such as Rails, then Sails will feel right at home.

Categories

Resources