MSSQL & Node.JS - Failed to connect to WIN-OTGKTVPUIFC:1433 - javascript

I have a problem when connect to SQL Server.
My config connect SQL Server:
const mssql = require('mssql');
const configMsSql = {
server:"myserver",
port:myport,
user:"username",
password:"pass",
database:"dbname",
options:{
trustServerCertificate: true
}
};
async function connectState(){
const connect = await mssql.connect(configMsSql);
console.log("Connect to SQL successfully!");
return connect;
}
module.exports = connectState();
After run server. mssql throw error:
err = new ConnectionError(err)
^
ConnectionError: Failed to connect to WIN-OTGKTVPUIFC:1433 - 7C250000:error:0A000102:SSL routines:ssl_choose_client_version:unsupported protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1986:
at C:\UIS\SboxNode\node_modules\mssql\lib\tedious\connection-pool.js:70:17
at Connection.onConnect (C:\UIS\SboxNode\node_modules\tedious\lib\connection.js:1020:9)
at Object.onceWrapper (node:events:628:26)
at Connection.emit (node:events:513:28)
at Connection.emit (C:\UIS\SboxNode\node_modules\tedious\lib\connection.js:1048:18)
at Connection.socketError (C:\UIS\SboxNode\node_modules\tedious\lib\connection.js:1399:12)
at C:\UIS\SboxNode\node_modules\tedious\lib\connection.js:2406:25
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: 'ESOCKET',
originalError: ConnectionError: Failed to connect to WIN-OTGKTVPUIFC:1433 - 7C250000:error:0A000102:SSL routines:ssl_choose_client_version:unsupported protocol:c:\ws\deps\openssl\openssl\ssl\statem\statem_lib.c:1986:
at Connection.socketError (C:\UIS\SboxNode\node_modules\tedious\lib\connection.js:1399:28)
at C:\UIS\SboxNode\node_modules\tedious\lib\connection.js:2406:25
at process.processTicksAndRejections (node:internal/process/task_queues:95:5) {
code: 'ESOCKET',
isTransient: undefined
}
}
Node.js v18.12.1
Although I enabled TCP/IP and field TCP Port used exactly.
I tried to search gg this error but the most answer that "enable TCP/IP".
I spent many time to fix but cant. Help me plzz :(

Related

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)

No stream features to proceed using node-xmpp-client

I've installed prosody on an ubuntu AWS server. I have tried using Adium client and swift, but I get the same error indicated in the title. I've tried using node-xmpp-client to create a client but same error.
Node-XMPP client code:
const Client = require('node-xmpp-client');
const options = {
jid: 'test#ec2-18-222-249-134.us-east-2.compute.amazonaws.com',
password: 'password',
host: 'ec2-18-222-249-134.us-east-2.compute.amazonaws.com'
}
const client = new Client(options);
client.once('online', connectionDetails =>{
console.log('We are connected');
console.log(connectionDetails);
});
Error Message:
Error: No stream features to proceed with
at Connection.onStanza (/Users/my-name/BeginXMPP/node_modules/node-xmpp-core/lib/Connection.js:363:17)
at StreamParser.<anonymous> (/Users/my-name/BeginXMPP/node_modules/node-xmpp-
core/lib/Connection.js:231:10)
at StreamParser.emit (events.js:198:13)
at SaxLtx.<anonymous> (/Users/my-name/BeginXMPP/node_modules/#xmpp/streamparser/index.js:69:14)
at SaxLtx.emit (events.js:198:13)
at SaxLtx._handleTagOpening (/Users/my-name/BeginXMPP/node_modules/ltx/lib/parsers/ltx.js:40:12)
at SaxLtx.write (/Users/my-name/BeginXMPP/node_modules/ltx/lib/parsers/ltx.js:159:18)
at StreamParser.write (/Users/my-name/BeginXMPP/node_modules/#xmpp/streamparser/index.js:134:17)
at Connection.onData (/Users/my-name/BeginXMPP/node_modules/node-xmpp-core/lib/Connection.js:310:17)
at Socket.emit (events.js:203:15)
Emitted 'error' event at:
at Client.<anonymous> (/Users/my-name/BeginXMPP/node_modules/node-xmpp-client/lib/Client.js:158:23)
at Connection.emit (events.js:203:15)

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.

NodeJS HTTPS API testing with mocha and super test -"CERT_HAS_EXPIRED"

I need to test an API served via HTTPS with mocha and super test
This is a gist of the server :
...
var app = express();
var _options = {
key: fs.readFileSync('my-key.pem');,
cert: fs.readFileSync('my-cert.pem')
};
// Start HTTPS server
https.createServer(_options, app).listen(app.get('port'), app.get('ip'), function () {
// ok or not logs
});
and this is the route to be tested
app.get('/hello',function (req, res) {
res.json(200);
});
I'm trying to test with this code in test/test.js
var supertest = require('supertest'),
api = supertest('https://localhost:3000');
describe('Hello test', function () {
it('hello', function (done) {
api.get('/hello')
.expect(200)
.end(function (err, res) {
if (err) {
done(err);
} else {
done();
}
});
});
});
but the test FAILs with the following error :
Error: CERT_HAS_EXPIRED
at SecurePair.<anonymous> (tls.js:1349:32)
at SecurePair.EventEmitter.emit (events.js:92:17)
at SecurePair.maybeInitFinished (tls.js:962:10)
at CleartextStream.read [as _read] (tls.js:463:15)
at CleartextStream.Readable.read (_stream_readable.js:320:10)
at EncryptedStream.write [as _write] (tls.js:366:25)
at doWrite (_stream_writable.js:219:10)
at writeOrBuffer (_stream_writable.js:209:5)
at EncryptedStream.Writable.write (_stream_writable.js:180:11)
at write (_stream_readable.js:573:24)
at flow (_stream_readable.js:582:7)
at Socket.pipeOnReadable (_stream_readable.js:614:5)
at Socket.EventEmitter.emit (events.js:92:17)
at emitReadable_ (_stream_readable.js:408:10)
at emitReadable (_stream_readable.js:404:5)
at readableAddChunk (_stream_readable.js:165:9)
at Socket.Readable.push (_stream_readable.js:127:10)
at TCP.onread (net.js:526:21)
While using plain HTTP the test is PASSING
Have you taken the error message at face value already? Is the certificate you are using to test expired? Is the clock way off on the machine? Also note that TLS certificates are associated with a host name and that host name is generally not "localhost" if you want to do anything useful. Assuming it's not the obvious error of the certificate being expired, try using exactly the correct hostname when connecting to your server.

Categories