fetch error message reason get addrinfo ENOTFOUND localhost - javascript

I'm making a slack clone with socket.io and node with a mongodb cluster. everything worked fine this weekend until today when i opened the project and noticed a message I've never seen before:
(node:31352) UnhandledPromiseRejectionWarning: FetchError: request to http://localhost:5000/chat failed, reason: getaddrinfo ENOTFOUND localhost
at ClientRequest. (/Users/philiplagergrenydehed/git/slack-clone/slack-clone/node_modules/node-fetch/lib/index.js:1455:11)
at ClientRequest.emit (events.js:219:5)
at Socket.socketErrorListener (_http_client.js:420:9)
at Socket.emit (events.js:219:5)
at emitErrorNT (internal/streams/destroy.js:84:8)
at processTicksAndRejections (internal/process/task_queues.js:84:21)
(node:31352) 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)
What does this mean and how do i fix it?
This is my fetch but I cannot see anything wrong with it.
router.post('/new', function (req, res, next) {
console.log(req.body)
const messageObject = {
channelID: '437469384738473894',
name: req.body.name,
time: req.body.time,
text: req.body.message
}
const option = {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(messageObject)
};
try{
fetch('http://localhost:5000/chat', option)
.then(response => {
response.json()
.then(function(data){
response.send(data)
});
});
} catch{
res.send("error")
}
})
I'm stuck and I really need your help!!

Related

How to handle a possible uncatchable error in Javascript?

I've got a very small program in index.js, it tries to make a connection to a URL that does not exist, and makes a request within that connection. When that happens I want to catch and handle any errors, but I'm getting an ENOTFOUND raised and it forces my program to exit. How do I go about catching this error and handling it properly?
Index.js:
const jsforce = require("jsforce");
conn = new jsforce.Connection({
accessToken: "",
instanceUrl: "http://thisdoesnotexistalsdkfjalsdkfjasdlkfjasdlkfjalsdkfja.com",
version: "51.0",
callOptions: {
client: `sf-fx-runtime-nodejs-sdk-impl-v1:1`
}
});
const response = conn.query("SELECT foo from bar");
console.log(response);
response.then(
undefined,
function foo(e) {
console.log("======================== lol")
console.log(e)
})
Actual:
$ node index.js
/Users/rschneeman/Documents/projects/work/nodejs-uncatachable-error-maybe/node_modules/node-fetch/lib/index.js:1461
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
^
FetchError: request to http://thisdoesnotexistalsdkfjalsdkfjasdlkfjasdlkfjalsdkfja.com/services/data/v51.0/query?q=SELECT%20foo%20from%20bar failed, reason: getaddrinfo ENOTFOUND thisdoesnotexistalsdkfjalsdkfjasdlkfjasdlkfjalsdkfja.com
at ClientRequest.<anonymous> (/Users/rschneeman/Documents/projects/work/nodejs-uncatachable-error-maybe/node_modules/node-fetch/lib/index.js:1461:11)
at ClientRequest.emit (node:events:369:20)
at Socket.socketErrorListener (node:_http_client:462:9)
at Socket.emit (node:events:369:20)
at emitErrorNT (node:internal/streams/destroy:188:8)
at emitErrorCloseNT (node:internal/streams/destroy:153:3)
at processTicksAndRejections (node:internal/process/task_queues:81:21) {
type: 'system',
errno: 'ENOTFOUND',
code: 'ENOTFOUND'
}
Expected:
$ node index.js
======================== lol
reject(new FetchError(`request to ${request.url} failed, reason: ${err.message}`, 'system', err));
(logged but doesn't force exit the process)
Your case seems like a try/catch situation. You can do something like:
try {
//do stuff
catch (error) {
//handle your error
}
You might also want to take a look at Promises.

Node events.js:174 throw er; // Unhandled 'error' event

I get an error when requesting an API and it crashes on any win server. Can anybody help, please?
This is part of my code:
app.get("/js/2806/api/products/getAllDrugs", (req, res) => {
const connection = getDBConnection()
const queryString = "SELECT * FROM tbl_drug";
connection.query(queryString, (err, rows, fields) => {
if (err) {
console.log("Failed to query for drugs: " + err);
// res.sendStatus(500);
res.json({
ErrorDetail: {
code: -1,
msg: err.code
}
});
res.end();
return
}
const drugs = rows.map((row) => {
return {
id: row.id,
storeId: row.drugStoreId,
drugName: row.drugName,
description: row.drugDsc,
drugUsing: row.drugUsing,
drugDoseId: row.drugDoseId,
categoryId: row.categoryId
};
})
res.json({
ErrorDetail: {
code: 0
},
Response: drugs
})
})
});
Error: Connection lost: The server closed the connection. at Protocol.end (C:\Users\Administrator\AppData\Local\CaptainCure\n s\mysql\lib\protocol\Protocol.js:112:13) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:97:28) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:502:10) at Socket.emit (events.js:194:15) at endReadableNT (_stream_readable.js:1125:12) at process._tickCallback (internal/process/next_tick.js:63:19) Emitted 'error' event at: at Connection._handleProtocolError (C:\Users\Administrator\AppData\ ainCure\node_modules\mysql\lib\Connection.js:425:8) at Protocol.emit (events.js:189:13) at Protocol._delegateError (C:\Users\Administrator\AppData\Local\Ca node_modules\mysql\lib\protocol\Protocol.js:390:10) at Protocol.end (C:\Users\Administrator\AppData\Local\CaptainCure\n s\mysql\lib\protocol\Protocol.js:116:8) at Socket. (C:\Users\Administrator\AppData\Local\Captain odules\mysql\lib\Connection.js:97:28) I— lines matching original stack trace ...] at process._tickCallback Cinternal/process/next_tick.js:63:19> [nodemon I - wait in is (nodemon] si ing 'node app.js -erver is running on port: 3000 ode events.js:174 throw er; // Unhandled 'error' event is (nodemon] starting 'node app.js' -erver is running on port: 3000
Because of the server is already running on back so we do have to restart.
and if your using both iterm and the terminal so you need to make sure that the you use only one other one you have to close.

How to fix MaxListenersExceededWarning error?

In my Node.js http web server I use ssh2-sftp-client library to load csv files from remote SFTP server. It raise error when user try to load several files and I don't understand how to fix it?
CODE:
router.post('/', (req, res) => {
const fileName = req.body.file_name
const remotePath = '/reports/' + fileName
const localePath = path.join(process.env.HOME || process.env.USERPROFILE, 'Downloads/' + fileName)
sftp.connect(config.sftpServer, 'on').then(() => {
sftp.fastGet(remotePath, localePath, {}).then(() => {
res.header('Content-type', 'text/csv; charset=windows-1251')
res.sendFile(localePath)
sftp.end()
}).catch((err) => {
sftp.end()
console.log(err, 'fastGet method error')
})
}).catch((err) => {
sftp.end()
console.log(err, 'connect method error')
})
})
ERROR:
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Error: Failed to connect to server: (SSH) Channel open failure: open failed
at client.sftp (/node_modules/ssh2-sftp-client/src/index.js:456:18)
at /node_modules/ssh2/lib/client.js:867:14
at SSH2Stream.onFailure (/node_modules/ssh2/lib/client.js:1211:5)
at Object.onceWrapper (events.js:277:13)
at SSH2Stream.emit (events.js:189:13)
at parsePacket (/node_modules/ssh2-streams/lib/ssh.js:3709:10)
at SSH2Stream._transform (/node_modules/ssh2-streams/lib/ssh.js:671:13)
at SSH2Stream.Transform._read (_stream_transform.js:190:10)
at SSH2Stream._read (/node_modules/ssh2-streams/lib/ssh.js:253:15)
at SSH2Stream.Transform._write (_stream_transform.js:178:12) 'connect method error'
Finally I found the problem. Instead of on method you need to use once method.
sftp.connect(config.sftpServer, 'once').then(() => {
// CODE
}

node js heroku interact with postgresql

I am trying to add a PostgreSQL database to my existing nodejs project on heroku. I am having trouble accessing the local version of the database at all, and also having trouble writing to the heroku database.
Here is part of the code that I have tried:
const { Client } = require('pg');
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
client.connect();
// client
let qu = 'SELECT table_schema,table_name FROM information_schema.tables;';
//qu = 'CREATE TABLE test (name varchar(40));';
//qu = 'SELECT * FROM test;';
// qu = 'INSERT INTO test name VALUES("testasdf");';
// qu = 'CREATE DATABASE X
client.query(qu, (err, res) => {
//console.log("trying");
if (err) throw err;
for (let row of res.rows) {
console.log(JSON.stringify(row));
}
client.end();
});
I have tried following the instructions here: https://devcenter.heroku.com/articles/heroku-postgresql
but I can't access the local database or do anything to the remote one.
Here is the local error message:
(node:8402) UnhandledPromiseRejectionWarning: error: password authentication failed for user "..."
at Connection.parseE (.../theland/node_modules/pg/lib/connection.js:553:11)
at Connection.parseMessage (.../theland/node_modules/pg/lib/connection.js:378:19)
at TLSSocket. (.../theland/node_modules/pg/lib/connection.js:119:22)
at emitOne (events.js:116:13)
at TLSSocket.emit (events.js:211:7)
at addChunk (_stream_readable.js:263:12)
at readableAddChunk (_stream_readable.js:250:11)
at TLSSocket.Readable.push (_stream_readable.js:208:10)
at TLSWrap.onread (net.js:597:20)
(node:8402) 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:8402) [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 don't know how to create a table on the remote one.
I am running on Linux with
node-v = 8.11.2
npm-v = 6.1.0
pg: ^7.4.3
I am using psql too, no GUI.
Thanks for the help.
EDIT---
Where should I add the authentication? Do I need to take the script off of github if I add the authentication and don't want people to be able to be admins for my database?
password authentication failed for user "..."
Obviously you are not using the right password for the user. The positive news is that there is a server responding your request.
Unhandled promise rejection
There is an error, probably thrown here:
if (err) throw err;
You seem not to catch it somewhere, you only throw it. Try to put it into some try-catch-block, e.g. like
function queryDatabase() {
try {
const client = new Client({
connectionString: process.env.DATABASE_URL,
ssl: true,
});
client.connect();
// client
let qu = 'SELECT table_schema,table_name FROM information_schema.tables;';
//qu = 'CREATE TABLE test (name varchar(40));';
//qu = 'SELECT * FROM test;';
// qu = 'INSERT INTO test name VALUES("testasdf");';
// qu = 'CREATE DATABASE X
client.query(qu, (err, res) => {
//console.log("trying");
if (err) throw err;
for (let row of res.rows) {
console.log(JSON.stringify(row));
}
client.end();
});
} catch (error) {
// if you need further help, remember to provide this error here.
console.log(error);
}
}

SSL Error in nodejs request package

I'm trying to call freecodecamp api #url https://forum.freecodecamp.org/c/getting-a-developer-job.json?
I am doing some analysis on the data, but when I call this service using 'request' npm package I am getting ssl error as follows:
error { Error: write EPROTO 140735782093632:error:14094410:SSL routines:ssl3_read_bytes:sslv3 alert handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:1500:SSL alert number 40
140735782093632:error:1409E0E5:SSL routines:ssl3_write_bytes:ssl handshake failure:../deps/openssl/openssl/ssl/s3_pkt.c:659:
at _errnoException (util.js:1022:11)
at WriteWrap.afterWrite [as oncomplete] (net.js:867:14) code: 'EPROTO', errno: 'EPROTO', syscall: 'write' }
Can somebody let me know what the issue is? A wget call pulls the data when provided with --ca-certificate option, also the webservice is giving data to postman without any certificate.
Here is my code:
import request from 'request';
import fs from 'fs';
const BASE_URL = 'forum.freecodecamp.org/c/getting-a-developer-job.json?no_subcategories=false&page=1';
request.get(BASE_URL, {
port: 443,
agentOptions: {
ciphers: 'ALL',
ca: fs.readFileSync('./mycertfile.pem'),
secureProtocol: 'TLSv1_2_method'
},
strictSSL: false
})
.on('response', (response) => {
console.log('Response is ', response);
}).on('error', (err) => {
console.log('error', err);
});
I see no problems there except URI http:// is absent, in my environment i have node v10.5.0, and the slightly modified version of your script works well:
const request = require('request')
const BASE_URL = 'https://forum.freecodecamp.org/c/getting-a-developer-job.json?no_subcategories=false&page=1'
request.get(BASE_URL, { json: true }, (err, res, body) => {
if (err) throw('error', err);
console.log('JSON object is => ', body);
})
outputs to console:
JSON object is => { users:
[ { id: 117390,
username: 'anthony2025',
....

Categories

Resources