net.createConnection ECONNREFUSED - javascript

net.createConnection always seems to give ECONNREFUSED. I did a tcpdump and don't quite know what I'm looking for.
Code:
const net = require('net');
const client = net.createConnection({ port: 8124}, () => {
// 'connect' listener.
console.log('connected to server!');
client.write('world!\r\n');
});
client.on('error', function(e) {
console.log(e);
console.log(e.message);
});
client.on('data', (data) => {
console.log(data.toString());
client.end();
});
client.on('end', () => {
console.log('disconnected from server');
});
Output:
Error: connect ECONNREFUSED 127.0.0.1:8124
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16) {
errno: -4078,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8124
}
connect ECONNREFUSED 127.0.0.1:8124
Link to the pcap file to view the packets Click me

Use a tracer like tcpdump to see what is actually going on. The message, "connection refused," is actually a bit misleading. It doesn't actually mean that the host has identified you and is now refusing to talk to you.

Make sure you have a server running on port 8124 of your local machine (127.0.0.1). ECONNREFUSED means you dont.

Related

how can I get status code when I get an erroruse axios

I want to get an object when the HTTP request failed.
something like this
Object = {status: 404, reason: 'Not found', body: '404 Not found'}
I have read How can I get the status code from an HTTP error in Axios?,But It does not work for me.
This is the JS code,
const axios = require('axios');
axios({
url:'https://www.icofont.cn//sd',
method:'GET',
})
.then(response=>{
console.log(response.status);
})
.catch(error=>{
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
})
I always get an undefined of the error.response.So I get an error. I can get an error object. How can I extract 404 Not found from this object?
The problem is that you are assuming the error is returned in the response. It could also be in the request (e.g. while connecting to the server before making the request). I addded console.log(error) and found that on my computer the error is in the request:
AxiosError: connect ECONNREFUSED 38.238.92.52:443
at AxiosError.from (/run/user/1000/test123/node_modules/axios/dist/node/axios.cjs:725:14)
at RedirectableRequest.handleRequestError (/run/user/1000/test123/node_modules/axios/dist/node/axios.cjs:2467:25)
at RedirectableRequest.emit (node:events:513:28)
at eventHandlers.<computed> (/run/user/1000/test123/node_modules/follow-redirects/index.js:14:24)
at ClientRequest.emit (node:events:513:28)
at TLSSocket.socketErrorListener (node:_http_client:494:9)
at TLSSocket.emit (node:events:513:28)
at emitErrorNT (node:internal/streams/destroy:151:8)
at emitErrorCloseNT (node:internal/streams/destroy:116:3)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
port: 443,
address: '38.238.92.52',
syscall: 'connect',
code: 'ECONNREFUSED',
errno: -111,
config: {
[...]
},
request: <ref *1> Writable {
[...]
},
cause: Error: connect ECONNREFUSED 38.238.92.52:443
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1300:16) {
errno: -111,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '38.238.92.52',
port: 443
}
}
/run/user/1000/test123/test.js:11
console.log(error.response.data);
^
TypeError: Cannot read properties of undefined (reading 'data')
at /run/user/1000/test123/test.js:11:32
at process.processTicksAndRejections (node:internal/process/task_queues:95:5)
Node.js v18.10.0
The server you are connecting to does not seem to support HTTPS. It can only be connected to if https://www.icofont.cn//sd is changed to http://www.icofont.cn//sd, and then the 404 comes out.
Instead of assuming the error is in the response or request, it should be checked for. The official example explains this.
Your fixed example will look like the following:
const axios = require('axios');
axios({
url:'http://www.icofont.cn//sd',
method:'GET',
})
.then(response=>{
console.log(response.status);
})
.catch(error=>{
if (error.response) {
// The request was made and the server responded with a status code
// that falls out of the range of 2xx
console.log(error.response.data);
console.log(error.response.status);
console.log(error.response.headers);
} else if (error.request) {
// The request was made but no response was received
// `error.request` is an instance of XMLHttpRequest in the browser and an instance of
// http.ClientRequest in node.js
console.log(error.request);
} else {
// Something happened in setting up the request that triggered an Error
console.log('Error', error.message);
}
console.log(error.config);
})

Why Can't I connect SQL Server to my node js

I'm using the 'mssql' npm package to connect my SQL server to my node JS.
I went through a few questions, but it wasn't solved anywhere.
My SQL Server login credentials are-
server type : Database Engine
Server name : DESKTOP-MPF88ST\KUSHAL
authentication : sql server authentication
login : username
password : password
and the database I wanna get is schoolDB
and my code goes something like this
const sql =require("mssql")
const config = {
login: 'username',
password:'password',
server: 'localhost',
database: "schoolDB",
options : {
enableArithAbort: true
},
port : 1433
}
sql.connect(config, (err) => {
if(err){
console.log(err);
}
else {
console.log("Connected")
}
I have my TCP/IP enabled and set up, SQL Server Browser enabled, but it still throws the error-
ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at Connection.<anonymous> (E:\Kushals\server\node_modules\mssql\lib\tedious\connection-pool.js:68:17)
at Object.onceWrapper (events.js:422:26)
at Connection.emit (events.js:315:20)
at Connection.socketError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:12)
at E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at SequentialConnectionStrategy.connect (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:87:14)
at Socket.onError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:100:12)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3) {
code: 'ESOCKET',
originalError: ConnectionError: Failed to connect to localhost:1433 - Could not connect (sequence)
at ConnectionError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\errors.js:13:12)
at Connection.socketError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1290:56)
at E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connection.js:1116:21
at SequentialConnectionStrategy.connect (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:87:14)
at Socket.onError (E:\Kushals\server\node_modules\mssql\node_modules\tedious\lib\connector.js:100:12)
at Socket.emit (events.js:315:20)
at emitErrorNT (internal/streams/destroy.js:92:8)
at emitErrorAndCloseNT (internal/streams/destroy.js:60:3)
at processTicksAndRejections (internal/process/task_queues.js:84:21) {
code: 'ESOCKET'
}
}
How can I solve it ??
Try this:
const sql = require('mssql/msnodesqlv8')
const pool = new sql.ConnectionPool({
login: 'username',
password:'password',
database: 'schoolDB',
server: 'DESKTOP-MPF88ST\KUSHAL',
driver: 'msnodesqlv8',
options: {
trustedConnection: true
}
})
pool.connect().then(() => {
//sample query
pool.request().query('select 1 as number', (err, result) => {
console.dir(result)
})
})
Ensure that the TCP/IP protocol is Enabled as it is disabled by default.
Steps:
Go to Computer management
Under Service and Applications -> SQL Server Configuration Manager
-> SQL Server Network configuration -> click on "Protocols for MSSQLSERVER"
You will see TCP/IP section (to enable right click and enable it)

How to connect Mongo Atlas Database in Lambda function with Mongoose

I am using Serverless framework to deploy my backend to API Gateway and AWS Lambda.
Here is my serverless.yml for this specific lambda function.
It is a cron job that runs every hour.
cron:
handler: handler.transferHandler
events:
- schedule: rate(1 hour)
Now when I test on localhost it works perfectly. But when I deploy to aws I get the following error:
MongoDB connection error. Please make sure MongoDb is running. { MongoError: failed to connect to server [undefined:27017] on first connect [MongoError: getaddrinfo ENOTFOUND undefined undefined:27017]
at Pool.<anonymous> (/var/task/node_modules/mongodb-core/lib/topologies/server.js:336:35)
at emitOne (events.js:96:13)
at Pool.emit (events.js:188:7)
at Connection.<anonymous> (/var/task/node_modules/mongodb-core/lib/connection/pool.js:280:12)
at Connection.g (events.js:292:16)
at emitTwo (events.js:106:13)
at Connection.emit (events.js:191:7)
at Socket.<anonymous> (/var/task/node_modules/mongodb-core/lib/connection/connection.js:189:49)
at Socket.g (events.js:292:16)
at emitOne (events.js:96:13)
at Socket.emit (events.js:188:7)
at connectErrorNT (net.js:1021:8)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
name: 'MongoError',
message: 'failed to connect to server [undefined:27017] on first connect [MongoError: getaddrinfo ENOTFOUND undefined undefined:27017]' }
Here is my function in my handler.js:
exports.transferHandler = function transferHandler(event, context) {
context.callbackWaitsForEmptyEventLoop = false;
mongoose.connect(mongoString, {useMongoClient: true});
const db = mongoose.connection;
db.on("error", (err) => {
console.log("MongoDB connection error. Please make sure MongoDb is running.", err);
process.exit();
});
db.once('open', () => {
BookingModel
.find({})
.then((bookings) => {
...
})
.catch((err) => {
console.log(err);
})
.finally(() => {
db.close();
});
});
};
After 2 weeks of being stuck on this, I learned that I needed to specify my environment variables in my serverless.yml for it to work. My functions were never connecting to the database because my mongo string was never set in lambda. Hope this helps someone.
provider:
name: aws
runtime: nodejs6.10
stage: production
region: us-west-1
environment:
MONGODB_URL: ${env:MONGODB_URL}
S3_BUCKET: ${env:S3_BUCKET}
S3_BUCKET_REPORT: ${env:S3_BUCKET_REPORT}
STRIPE_CLIENT_ID: ${env:STRIPE_CLIENT_ID}
STRIPE_PUBLIC_KEY: ${env:STRIPE_PUBLIC_KEY}
STRIPE_SECERET_KEY: ${env:STRIPE_SECERET_KEY}
JWT_SECRET: ${env:JWT_SECRET}
SEND_BIRD_TOKEN: ${env:SEND_BIRD_TOKEN}
SEND_BIRD_APP_ID: ${env:SEND_BIRD_APP_ID}
MANDRILL_APIKEY: ${env:MANDRILL_APIKEY}

Socket.IO adapter throws uncatchable Timed Out error on MongoDB disconnection

I'm trying to catch mongodb disconnection event.
It works fine with the following setup:
simple.js
'use strict';
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/pnsockets', function () {
console.log('mongoose connected');
});
mongoose.connection.on('disconnected', function () {
console.log('mongoose disconnected');
});
If simple.js is running and I stop mongodb (launchctl stop homebrew.mxcl.mongodb), I get mongoose disconnected on the console, and I can handle the issue.
But running extended.js that is usung socket.io-adapter-mongo, when I kill mongodb, I get the following error:
/project/node_modules/mongoose/node_modules/mongodb/lib/utils.js:98
process.nextTick(function() { throw err; });
^
MongoError: server localhost:27017 timed out
at null.<anonymous> (/project/node_modules/mongodb-core/lib/topologies/server.js:436:40)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at null.<anonymous> (/project/node_modules/mongodb-core/lib/connection/pool.js:144:10)
at g (events.js:260:16)
at emitTwo (events.js:87:13)
at emit (events.js:172:7)
at Socket.<anonymous> (/project/node_modules/mongodb-core/lib/connection/connection.js:172:12)
at Socket.g (events.js:260:16)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at TCP._onclose (net.js:468:12)
extended.js
'use strict';
var mongoose = require('mongoose');
var socketIO = require('socket.io');
var MongoAdapter = require('socket.io-adapter-mongo');
mongoose.connect('mongodb://localhost:27017/pnsockets', function () {
console.log('mongoose connected');
_setupSocketAdapter();
});
mongoose.connection.on('disconnected', function () {
console.log('mongoose disconnected');
});
var _setupSocketAdapter = function () {
var io = socketIO();
var socket = mongoose.connections[0].db;
socket.connection = mongoose.connections[0]; // mubsub will need this line
var mongoAdapter = MongoAdapter({socket: socket});
io.adapter(mongoAdapter);
};
How can I catch the MongoError: server localhost:27017 timed out error?
The problem is coming from socket.io-adapter-mongo itself.
If you take a look at the source code, they're using mubsub. Mubsub is basically a pub / sub implementation for Node.js and MongoDB.
They're setting up a client and a channel which is mapping one-to-one with a capped collection but there is no event handler attached on these parts.
According to the mubsub documentation, the following event are available on a channel: *, message, document, ready and error. The error event is also available on the client.
For example, simply adding the following code would catch the errors you're having.
channel.on('error', function (err) {
console.error(err.message);
});
client.on('error', function (err) {
console.error(err.message);
});
In case of a disconnection, you'll get the following output instead of the unhandled error.
mongoose connected
server localhost:27017 timed out
mongoose disconnected
Mubsub: broken cursor.

node net socket timeout error on client

This is my server side code which has been hosted on IBM Bluemix,
const net = require('net');
const server = net.createServer((c) => { //'connection' listener
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
server.listen(8124, () => { //'listening' listener
console.log('server bound');
});
I am using below code as client on local,
var net = require('net');
var HOST = 'xxx.xx.xx.xx';
var PORT = xxxx;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('I am Chuck Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});
When I run, It throws error Like.
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT xxx.xx.xx.xx:xxxx
at Object.exports._errnoException (util.js:856:11)
at exports._exceptionWithHostPort (util.js:879:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14) vivek#vivek-Latitude-E6220:/var/www/html/test/NODE/net$ node client.js
events.js:141
throw er; // Unhandled 'error' event
^
Error: connect ETIMEDOUT xxxx.xx.xx.xx:xxxx
at Object.exports._errnoException (util.js:856:11)
at exports._exceptionWithHostPort (util.js:879:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1063:14)
When I run the server code on local, It works perfect. Kindly help me to find the error.
You need to listen on the port that Bluemix assigns for your application. Bluemix will assign your application a port and you will need to bind on that port. Bluemix will load balance to your application and have your application available on ports 443 and 80.
You can get the port with the following code.
var port = process.env.PORT || 8124;
Also you don't need to bind to a host either.
I modified your code below.
const net = require('net');
const server = net.createServer((c) => { //'connection' listener
console.log('client connected');
c.on('end', () => {
console.log('client disconnected');
});
c.write('hello\r\n');
c.pipe(c);
});
var port = process.env.PORT || 8124;
server.listen(port, () => { //'listening' listener
console.log('server bound');
});
The client code tries to connect to the server at the wrong address. Make sure that the client code's IP address and port number match the server's IP address and port number.
Also, ensure that the server is running and that the network connection between the server and the client is open. If the issue persists, try using a different port number and make sure the port is available on the server.
There is a read ECONNRESET Error in your server, when client destroy the socket.
you can catch using
c.on('error', function(err) {
console.log('SOCKET ERROR : ' , err);
});
you can avoid the crash this way.
working version for me, based on your code
server.js
const net = require('net');
var server = net.createServer(function(c) {
console.log('client connected');
c.on('end', function(c) {
console.log('sendHomeKeytoIosDevice : ERROR : ' + c);
});
c.on('error', function(err) {
console.log('sendHomeKeytoIosDevice : ERROR : ' + err);
});
c.write('hello\r\n');
c.pipe(c);
});
server.listen(8124,function() {
console.log('server bound');
});
Client.js
var net = require('net');
var HOST = 'localhost';
var PORT = 8124;
var client = new net.Socket();
client.connect(PORT, HOST, function() {
console.log('CONNECTED TO: ' + HOST + ':' + PORT);
// Write a message to the socket as soon as the client is connected, the server will receive it as message from the client
client.write('I am Chuck Norris!');
});
// Add a 'data' event handler for the client socket
// data is what the server sent to this socket
client.on('data', function(data) {
console.log('DATA: ' + data);
// Close the client socket completely
client.destroy();
});
// Add a 'close' event handler for the client socket
client.on('close', function() {
console.log('Connection closed');
});

Categories