I'm trying to connect to a MQTT broker over TLS in react-native with MQTT.js. Based on the doc I tried this code:
const options = {
port: PORT,
host: HOST,
protocol: 'mqtts',
secureProtocol: 'TLS_method',
username: USERNAME,
password: PASSWORD,
ca: CA_FILE
}
const client = mqtt.connect(options);
client.on('error', (error) => {
console.log("error", error);
});
client.on('connect', () => {
console.log("connected");
});
The options object will be passed through tls.connect(), so I specified the certificate file.
The connection doesn't return an error, but the client is not connected.
What did I do wrong?
Try to use that fork of React native MQTT https://github.com/FrozenPyrozen/rn-native-mqtt it worked with TLS connection on Android and IOS
Related
i have issues on nodemailer transport using smtp which i developed in nodejs, it has no issues in local server and email sent correctly, but when i'm dockerize them and deploy to AWS ECS, the API still return status 200 without any error but email is not send to the clients email. how do i overcome this issues? i tried port 25 and 465 as well but still its not sending anything to client email.
const transporter = await nodemailer.createTransport({
host: 'smtp.office365.com',
port: 587,
auth: {
user: 'email#company.com.my',
pass: 'password'
},
})
const templates = new EmailTemplates()
await templates.render(template, context, async (err, html, text, subject) => {
await transporter.sendMail({
from: '"Company Name" <email#company.com.my>',
to: email,
subject: subjects,
html: html,
text: text
}).then(() => {
console.log(`Email sent to ${email}`)
}).catch((err) => {
console.log('error: ', err)
})
})
at first i though it's nodemailer issues, but then when i'm test run my local docker image, it's return an error
/srv/node_modules/html-to-text/lib/whitespace-processor.js:11
.map(c => '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'))
^
TypeError: c.charCodeAt(...).toString(...).padStart is not a function
at map.c (/srv/node_modules/html-to-text/lib/whitespace-processor.js:11:52)
at Array.map (native)
at charactersToCodes (/srv/node_modules/html-to-text/lib/whitespace-processor.js:11:6)
at new WhitespaceProcessor (/srv/node_modules/html-to-text/lib/whitespace-processor.js:32:29)
at new BlockTextBuilder (/srv/node_modules/html-to-text/lib/block-text-builder.js:28:31)
at htmlToText (/srv/node_modules/html-to-text/lib/html-to-text.js:146:19)
at Object.fromString (/srv/node_modules/html-to-text/lib/html-to-text.js:289:44)
at /srv/node_modules/swig-email-templates/index.js:50:29
at FSReqWrap.cb [as oncomplete] (fs.js:260:19)
i wonder what is the actual error and how to solve this html-to-text error?
I'm trying to build and deploy my app to OVH server, my client doesn't want a cloud solution, he want to host it or deploy it on OVH (they told me OVH support Node.js) and to be honest i have no idea how to do it.
my project work fine in development, its a Real-time chat with socket.io and MySql and some package as knex, in front-end i worked with React.js ( which i have no problem with it right now )
I can provide more informations if needed. thx a lot
const app = require("express")();
var cors = require("cors");
app.use(cors());
const server = require("http").createServer(app);
const mysql = require("mysql");
const knex = require("knex")({
client: "mysql",
connection: {
host: "localhost",
user: "root",
password: "",
database: "chat_message",
},
});
const io = require("socket.io")(server, {
cors: {
origin: "*",
credentials: true,
},
});
app.get("/messages", function (request, result) {
knex
.select()
.table("messages")
.then((data) => result.send(data))
});
io.on("connection", (socket) => {
socket.on("messageClient", (sms) => {
knex("messages")
.insert({
message: sms.msg,
socket_id: sms.id,
dateMsg: sms.Temps,
ip: sms.ip,
name: sms.name,
})
.then((e) => console.log("data insert succees"));
socket.broadcast.emit("messageAll", sms);
});
});
server.listen(5000, () => console.log("Port: 5000"));
OVH is a private company and I'm not sure if this would be offtopic and more suitable to ask their own support. However you should know that shared hosting in general does not support long running processes like nodejs. They only support PHP on the server.
I am setting up some websockets using ws library. I am struggling to set up authorisation using a handshake. I have added a route to our server to upgrade to a websocket connection like so:
.get(
'/chat',
authorisationFunction,
upgradeConnection,
),
The websocket server:
const WebSocket = require('ws');
const wss = new WebSocket.Server({ port: 3030 });
This is the upgradeConnection function, which will run if authorisation is successful:
const upgradeConnection = (request, socket, head) => {
return wss.handleUpgrade(request, request.socket, head, function done(ws) {
return wss.emit('connection', ws, request);
});
}
I also have a function that listens to messages:
function webSocketsServer() {
wss.on('connection', (ws, request, client) => {
ws.on('message', message => {
ws.send(message);
});
});
}
A connection gets emitted, and from my server I get this response:
HTTP/1.1 101 Switching Protocols
Upgrade: websocket
Connection: Upgrade
Sec-WebSocket-Accept: QyVvqadEcI1+ALka6j2pLKBkfNQ=
but then immediately on my client I get the error “WebSocket connection to 'ws://localhost:3000/chat’ failed: Invalid frame header”.
But when I bypass the handshake and connect directly to my websocket server, I can send messages successfully. The error is only on the client and not on the backend. What am I missing?
I am not 100% sure it is the only way but might help so I post it.
Based on this answer I would go for a server that uses the same port for http and websocket connections.
You can achieve it like this:
const { createServer } = require('http')
const ws = require('ws')
const express = require('express')
const app = express()
const server = createServer(app)
app.get('/', (req, res) => {
res.send('I am a normal http server response')
})
const wsServer = new ws.Server({
server,
path: '/websocket-path',
})
wsServer.on('connection', (connection) => {
connection.send('I am a websocket response')
})
server.listen(3030, () => {
console.log(`Server is now running on http://localhost:3030`)
console.log(`Websocket is now running on ws://localhost:3030/<websocket-path>`)
})
So your server listens on port 3030 for normal http requests. If it gets a websocket connection request on path '/websocket-path' it is passed to the the ws connection handler and from there you are good to go.
gun 0.8.8, Node.js-to-Node.js, Node.js-to-browser
I see the following error in browser console:
VM103:161 WebSocket connection to 'wss://127.0.0.1:8080/gun' failed: Error in connection establishment: net::ERR_INSECURE_RESPONSE
VM103:161 WebSocket connection to 'wss://10.42.0.56:8080/gun' failed: Error in connection establishment: net::ERR_CONNECTION_REFUSED
And there are no messages on Node.js side.
Sorce code of my server:
const Hapi = require('hapi');
const Gun = require('gun');
const pem = require('pem');
pem.createCertificate({ days: 1, selfSigned: true }, function (err, keys) {
if (err) {
throw err
}
const server = new Hapi.Server;
var tls = {
key: keys.serviceKey,
cert: keys.certificate
};
server.connection({
port: 8080,
tls
});
server.connections.forEach(c => Gun({ web: c.listener, file: 'data.json' }));
server.route({
method: 'GET',
path: '/',
handler: function (request, reply) {
reply('Server works!');
}
});
server.start();
})
In order to make gun work with a self-signed certificate you need two things:
Lunch browser ignoring the certificate errors. For example, Chrome
google-chrome --ignore-certificate-errors
Put the following process option in Node.js code
process.env.NODE_TLS_REJECT_UNAUTHORIZED = '0';
or add the environment variable
export NODE_TLS_REJECT_UNAUTHORIZED=0
When using the node-mysql npm package, is it possible to connect to the MySQL server using a SSH key instead of a password?
You can do the SSH tunnel component completely independently, and then point node-mysql (or any other sql client...) to your DB by using TCP tunneled over SSH.
Just set up your SSH tunnel like this
ssh -N -p 22 sqluser#remoteserverrunningmysql.your.net -L 33306:localhost:3306
Leave that going in the background (see articles like this for more in depth info).
Then just send any MySQL client to port 33306 on localhost. It will actually connect as though you are on your remote server and using port 3306.
Thanks so much Steve your answer help me alot. just to make it clearer use
ssh -f user#personal-server.com -L 2000:personal-server.com:25 -N
The -f tells ssh to go into the background just before it executes the command. This is followed by the username and server you are logging into. The -L 2000:personal-server.com:25 is in the form of -L local-port:host:remote-port. Finally the -N instructs OpenSSH to not execute a command on the remote system
To connect to mongo use whatever port you set as Local port (in this case the port is 2000)
For example let's say I want to connect on a remote server with IP 192.168.0.100 and mongo is running on port 27017.
Assume a user called elie with password eliepassword has access to ssh on port 22 I will have to do this
First run on the terminal the following :
ssh -f elie#192.168.0.100 -L 2002:127.0.0.1:27017 -N
In my mongo connection I will do :
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:2002/mydatabase');
module.exports = mongoose.connection;
I hope this makes it clear.
const mysql = require('mysql2');
const { Client } = require('ssh2');
const sshClient = new Client();
const dbServer = {
host: process.env.DB_HOST,
port: process.env.DB_PORT,
user: process.env.DB_USERNAME,
password: process.env.DB_PASSWORD,
database: process.env.DB_DATABASE
}
const tunnelConfig = {
host: process.env.DB_SSH_HOST,
port: 22,
username: process.env.DB_SSH_USER,
password: process.env.DB_SSH_PASSWORD
}
const forwardConfig = {
srcHost: '127.0.0.1',
srcPort: 3306,
dstHost: dbServer.host,
dstPort: dbServer.port
};
const SSHConnection = new Promise((resolve, reject) => {
sshClient.on('ready', () => {
sshClient.forwardOut(
forwardConfig.srcHost,
forwardConfig.srcPort,
forwardConfig.dstHost,
forwardConfig.dstPort,
(err, stream) => {
if (err) reject(err);
const updatedDbServer = {
...dbServer,
stream
};
const connection = mysql.createConnection(updatedDbServer);
connection.connect((error) => {
if (error) {
reject(error);
}
resolve(connection);
});
});
}).connect(tunnelConfig);
});