M Zayn
M Zayn

Reputation: 71

how to make socket io | node.js - with SSL working

i having an issue while using node.js with apache on site.

if using http without SSL node.js with apache are working with my domain at env. file If I remove the SSL code it runs fine, however with it I get a request to http://mydomain.io/socket.io/1/?t=XXXXXXXXX

but when i enable SSL with let encrypt

my site are working but connect with Node js + socket io having error 404

*Note it's not trying https, which causes it to fail.

I'm testing on chrome, firefox and edge still can't fix.

I apologize if this is a simple question, I'm a node/socket.io newbie.

Thanks!


Here my details code are working when using http | but not working using https with let encrypt domain

const pino = require('pino')
const https = require('https');
const { Boom } = require('@hapi/boom')
const fs = require('fs')
const chalk = require('chalk')
require('dotenv/config')
const express = require('express')
const socket = require("socket.io");
const { toDataURL } = require('qrcode')
const mysql = require('mysql');
require('dotenv').config();
const request = require('request');

const app = express()
const host = process.env.HOST ?? '127.0.0.1'
const port = parseInt(process.env.PORT ?? 3000)
app.use(express.urlencoded({ extended: true }))
app.use(express.json())
const ser = app.listen(port, host, () => {
    console.log(`Server is listening on http://${host}:${port}`)
})
const io = socket(ser);

const db = mysql.createConnection({
    host: process.env.DB_HOSTNAME,
    user: process.env.DB_USERNAME,
    password: process.env.DB_PASSWORD,
    database: process.env.DB_DATABASE
});

db.connect((err) => {
    if (err) throw err;
    console.log('Mysql Connected...');
});

const sessionMap = new Map()

Upvotes: 1

Views: 222

Answers (1)

Coder Gautam YT
Coder Gautam YT

Reputation: 2207

I've had a similar issue before, you need 2 Different servers, one for http, and one for https.

var usinghttps = false;
if(usinghttps) {
    var options = {
        key: fs.readFileSync("/etc/letsencrypt/live/us2.swordbattle.io/privkey.pem"),
        cert: fs.readFileSync("/etc/letsencrypt/live/us2.swordbattle.io/fullchain.pem"),
    };
 httpsserver = https.createServer(options, app).listen(443);
}
 server = http.createServer(app); 

And then to create the socket.io server,

const io = new Server(usinghttps ? httpsserver:server);

This personally worked for me, not sure if it works on all apps.

Upvotes: 1

Related Questions