Lost connection to server - Peer.js - javascript

Sometimes, in a very random way, the error "Lost connection to server" appears
Peerjs server code:
const { PeerServer } = require('peer');
const peerServer = PeerServer({ port: 80, host: 'ip' });
Peerjs connection code:
this.peer = new Peer('', {
host: 'peerjs server domain (uses cloudflare)',
port: 443,
debug: 2,
pingInterval: 2500,
secure: true,
path: '/',
config: {
iceServers: [
{
urls: [
'turn:coturnServerIP:3478',
'stun:coturnServerIP:3478'
],
username,
credential
}
]
}
});

Related

Switching from mqtts protocol to wss in nodeJS

I can connect to my MQTT broker, using mqtts protocol like this:
mqtt = require('mqtt')
let options = {
host: '0d9d5087c5b3492ea3d302aae8e5fd90.s2.eu.hivemq.cloud',
port: 8883,
path: '/mqtt',
clientId: 'mqttx_2d803d2743',
protocol: 'mqtts',
username: 'light29',
password: 'Mqtt29#!',
cleanSession: true,
}
// initialize the MQTT client
let client = mqtt.connect(options);
// setup the callbacks
client.on('connect', function () {
console.log('Connected');
});
client.on('error', function (error) {
console.log(error);
});
client.on('message', function (topic, message) {
// called each time a message is received
console.log('Received message:', topic, message.toString());
});
// subscribe to topic 'my/test/topic'
client.subscribe('mytest');
// publish message 'Hello' to topic 'my/test/topic'
client.publish('mytest', 'Hello');
This code, yields, as expected:
Connected
Received message: mytest Hello
Now, I would like to connect to this same broker but using wss protocol instead, thus I tried:
let options = {
host: '0d9d5087c5b3492ea3d302aae8e5fd90.s2.eu.hivemq.cloud',
port: 8884,
path: '/mqtt',
clientId: 'mqttx_2d803d2743',
protocol: 'wss',
username: 'light29',
password: 'Mqtt29#!',
cleanSession: true,
}
However, in this case, I got:
Error: connect ECONNREFUSED 127.0.0.1:8884
at TCPConnectWrap.afterConnect [as oncomplete] (node:net:1161:16) {
errno: -61,
code: 'ECONNREFUSED',
syscall: 'connect',
address: '127.0.0.1',
port: 8884
}
I have finally managed to connect with these changes:
let options = {
username: 'light29',
password: 'Mqtt29#!',
}
// initialize the MQTT client
let client = mqtt.connect('wss://0d9d5087c5b3492ea3d302aae8e5fd90.s2.eu.hivemq.cloud:8884/mqtt', options);
Still, I do not know why explicitly passing protocol, host, port and path does solve it.
The problem in the original is that protocol in the options should be schema and should container URL schema e.g.
let options = {
host: '0d9d5087c5b3492ea3d302aae8e5fd90.s2.eu.hivemq.cloud',
port: 8883,
path: '/mqtt',
clientId: 'mqttx_2d803d2743',
schema: 'mqtts://',
username: 'light29',
password: 'Mqtt29#!',
cleanSession: true,
}
or
let options = {
host: '0d9d5087c5b3492ea3d302aae8e5fd90.s2.eu.hivemq.cloud',
port: 8883,
path: '/mqtt',
clientId: 'mqttx_2d803d2743',
schema: 'wss://',
username: 'light29',
password: 'Mqtt29#!',
cleanSession: true,
}
protocol is not a valid option.

How to save winston log file into mysql database?

I've configured the winston logger like this :
import winston from "winston";
const { SqlTransport } = require("winston-sql-transport");
const transportConfig = {
client: "mysql2",
connection: {
host: "localhost",
user: "root",
password: "Mahdi54321",
database: "todos",
// port: "3307",
},
tableName: "logs",
};
const alignColorsAndTime = winston.format.combine(
winston.format.colorize({
all: true,
}),
winston.format.label({
label: "[LOGGER]",
}),
winston.format.timestamp({
format: "YYYY-MM-DD HH:mm:ss",
}),
winston.format.printf(
(info) => `${info.label} ${info.timestamp} ${info.level} : ${info.message}`
)
);
export const logger = winston.createLogger({
level: "debug",
transports: [
new winston.transports.Console({
format: winston.format.combine(
winston.format.colorize(),
alignColorsAndTime
),
}),
new winston.transports.File({
filename: "logs/example.log",
format: winston.format.combine(
winston.format.timestamp({
format: "YYYY-MM-DD HH:mm:ss",
}),
winston.format.json()
),
}),
new SqlTransport(transportConfig),
],
});
It only saves the first log and the next one is only saved in the file and not the database .
I'm guessing the new SqlTransport(transportConfig), doesn't run everytime so it can save every log to database .
How can I save every log one after another into mysql database ?
The package you use is deprecated, instead, you can use the winston-mysql package: https://www.npmjs.com/package/winston-mysql
implementation example as per documentation:
const options_default = {
host: 'localhost',
user: 'logger',
password: 'logger*test',
database: 'WinstonTest',
table: 'sys_logs_default'
};
//custom log table fields
const options_custom = {
host: 'localhost',
user: 'logger',
password: 'logger*test',
database: 'WinstonTest',
table: 'sys_logs_custom',
fields: {level: 'mylevel', meta: 'metadata', message: 'source', timestamp: 'addDate'}
};
//meta json log table fields
const options_json = {
host: 'localhost',
user: 'logger',
password: 'logger*test',
database: 'WinstonTest',
table: 'sys_logs_json'
};
const logger = winston.createLogger({
level: 'debug',
format: winston.format.json(),
defaultMeta: { service: 'user-service' },
transports: [
new winston.transports.Console({
format: winston.format.simple(),
}),
// or use: options_custom / options_json
new winstonMysql(options_default),
],
});
const rnd = Math.floor(Math.random() * 1000);
const msg = `test message ${rnd}`;
logger.debug(msg, {message: msg, type: 'demo'});
logger.error(msg, {message: msg, type: 'demo'});
logger.info(msg, {message: msg, type: 'demo'});
logger.warn(msg, {message: msg, type: 'demo'});

exporting consts from CommonJS app amd require them in another file

I want to export const config from config.js file in CommonJs app.
const config = {
development: {
client: 'pg',
connection: {
database: 'myDatabase',
user: 'myUser',
host: 'localhost',
password: 'password',
port: PORT,
ssl: {
rejectUnauthorized: false
}
},
server: {
host: '127.0.0.1',
port: 'PORT2'
}
}
module.exports = config;
and in index.js I require that like
var env = process.env.NODE_ENV || 'development';
const config = require('./config')[env];
const knexDB = knex({
client: config.client,
connection: {
database: config.database,
user: config.user,
host: config.host,
password: config.password,
port: config.port,
ssl: {
rejectUnauthorized: false
}
}
});
But in the config file. IntelliSense recommends changing module.exports to ES export which I don't want to do and keep the app CommonJS. also, config object in index.js I have this error :
Property 'host' does not exist on type '{ development: { client: string; connection: { database: string; user: string; host: string; password: string; port: number; ssl: { rejectUnauthorized: boolean; }; }; server: { host: string; port: string; }; }; production: { ...; }; }'.ts(2339)
How can I export config from config.js?
You're getting the wrong property of config. It must be config.development.host . give up on the vscode requesting a CommonJS module.leave it alone. You also have 2 options more to configure your constant data.
yarn add dotenv
npm install config
Check config file you Db details is inside config.development.connection but you are reading it from config.
const knexDB = knex({
client: config.development.client,
connection: {
database: config.development.connection.database,
user: config.development.connection.user,
host: config.development.connection.host,
password: config.development.connection.password,
port: config.development.connection.port,
ssl: {
rejectUnauthorized: false
}
}
But instead of this use config or env
well, I found a way to work around it. I removed connection from development and it worked! just mention I used config.connection.client and config.development.connection.client or other variables in the connection but still not working in the index.js.
so it looks like
const config = {
development: {
client: 'pg',
database: 'myDatabase',
user: 'myUser',
host: 'localhost',
password: 'password',
port: PORT,
ssl: {
rejectUnauthorized: false
}
server: {
host: '127.0.0.1',
port: 'PORT2'
}
}
module.exports = config;
and in index.js I access that like
const configure = require('./config.js')[env];
const knexDB = knex({
client: configure.client,
connection: {
database: configure.database,
user: configure.user,
host: configure.host,
password: configure.password,
port: configure.port,
ssl: {
rejectUnauthorized: false
}
}
});
thanks for everyone for thier contribution.

Heroku with Strapi, Application is not using production database

I've deployed my app to Heroku. It gives an Application Error message upon visit.
The logs gave me this:
[2021-02-15T01:04:05.882Z] debug ⛔️ Server wasn't able to start properly.
[2021-02-15T01:04:05.883Z] error Error: connect ECONNREFUSED 127.0.0.1:5432
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1146:16)
Which according to my guess, is that its trying to use local database. I think the app is not using the database.js located in config/env/production. The application runs fine with heroku local.
Below is the database.js I set for production env:
const parse = require("pg-connection-string").parse;
const config = parse(process.env.DATABASE_URL);
module.exports = ({ env }) => ({
defaultConnection: "default",
connections: {
default: {
connector: "bookshelf",
settings: {
client: "postgres",
host: config.host,
port: config.port,
database: config.database,
username: config.user,
password: config.password,
ssl: {
rejectUnauthorized: false,
},
},
options: {
ssl: true,
},
},
},
});
Creating and printing the config var on heroku console results in expected values.
For some reason the deployment method in the strapi docs to heroku does not seem to work when you initially have set up your local database as Postgres.
I had the same problem as you and I fixed it using the NODE_ENV env variable.
Instead of creating a new production database config file in ./config/production/database.js you can simply extend the config file in ./config/database.js with the prod config and decide based on what NODE_ENV is set which one to return.
As example:
module.exports = ({ env }) => {
const parse = require("pg-connection-string").parse;
const config = parse(env("DATABASE_URL", "127.0.0.1"));
const devConfig = {
client: "postgres",
connection: {
host: env("DATABASE_HOST", "127.0.0.1"),
port: env.int("DATABASE_PORT", 5432),
database: env("DATABASE_NAME", "db_name"),
user: env("DATABASE_USERNAME", "root"),
password: env("LOCAL_DB_PASSWORD"),
ssl: env.bool("DATABASE_SSL", false),
},
};
const prodConfig = {
client: "postgres",
connection: {
host: config.host,
port: config.port,
database: config.database,
user: config.user,
password: config.password,
ssl: {
rejectUnauthorized: false,
},
},
debug: false,
};
return
env("NODE_ENV", "development") === "production" ? prodConfig : devConfig
};

WebSocket Connection failed: error in connection establishment

The following code is client and server side code to use webRTC connection. It's working perfectly in localhost. when i deployed to linux shared hosting server., it's getting error.
This is my server side code.
var http = require('http');
var express = require('express');
var ExpressPeerServer = require('peer').ExpressPeerServer;
var app = express();
var server = http.createServer(app);
var options = {
debug: true,
key: 'peerjs',
allow_discovery: true,
ssl: {
key: '',
cert: ''
},
proxied: true
};
var expressPeerServer = ExpressPeerServer(server, options);
app.use('/api', expressPeerServer);
app.use('/', express.static('.'));
app.use('/list', function (req, res) {
return res.json(Object.keys(expressPeerServer._clients.peerjs));
});
var port = process.env.PORT || 8080;
server.listen(port, function () {
console.log('Basic-ss live at', port);
});
expressPeerServer.on('connection', function (id) {
console.log('Peer connected with id:', id);
});
expressPeerServer.on('disconnect', function (id) {
console.log('Peer %s disconnected', id);
});
the following is the client side code for connect peer.
initPeer(peerId) {
this.peer = new Peer(peerId, {
host: 'localhost',
port: 8080,
path: '/api',
key: 'peerjs',
debug: 3,
config: {
'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
]
}
});
setTimeout(() => {
this.currentPeerId = this.peer.id;
if (this.currentPeerId !== null) {
isPeerConnected = true;
} else {
isPeerConnected = false;
}
console.log('Current Peer ID', this.currentPeerId);
}, 4000);
}
this code is working perfectly in localhost.
this is the code i am uploading in server.
this.peer = new Peer(peerId, {
host: '', ===> my domain name here.
port: 8080,
path: '/api',
key: 'mebstelemedclinic',
debug: 3,
config: {
'iceServers': [
{ url: 'stun:stun.l.google.com:19302' },
{
url: 'turn:192.158.29.39:3478?transport=udp',
credential: 'JZEOEt2V3Qb0y27GRntt2u2PAYA=',
username: '28224511:1379330808'
}
]
}
});
if use the same server code and the above client side code., it's getting connection error.
WebSocket connection to 'wss://mydomain.in:8080/api/peerjs?key=peerjs&id=LY42201PH-yKy04f-ygqZJhqrBmezG6&token=n42tatqqn9e' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT
i was struck at this point from long time. Help me how can i overcome this error. thank you.
You should add the code below to your path nano site_name in /etc/nginx/sites-available:
location {
proxy_pass Ip address; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_set_header Host $host; }

Categories

Resources