I’m trying to run a code on Passenger that uses 2 servers, one of them express, the other websocket, and the Phusion Passenger Error: http error occurs.Server.listen() was called more than once, the code is attached
const express = require("express");
const mysql = require("mysql");
const cors = require("cors");
const path = require("path");
const ws = require("ws");
const fs = require("fs");
const { v4: uuid } = require("uuid");
const clients = {};
const log = fs.existsSync('log') && fs.readFileSync('log');
const messages = JSON.parse(log) || [];
const app = express();
const conport = 3000;
app.use(express.json());
app.use(cors());
const connection = mysql.createConnection({
host: '***',
user: '***',
password: '***!!!',
database: '***',
port: '***',
});
connection.connect((err) => {
if (err) {
console.error('Ошибка подключения к базе данных: ' + err.stack);
return;
}
console.log('Подключено к базе данных');
});
app.get('/api/dd', (req, res) => {
const sql = 'SELECT * FROM site_index';
connection.query(sql, (error, results, fields) => {
if (error) {
console.error('Ошибка выполнения SQL-запроса: ' + error);
res.status(500).send('Ошибка при получении данных из базы данных');
} else {
const importantText = results[0].importants;
const changesText = results[0].changes;
const eventsText = results[0].events;
res.json({ importantTxt: importantText, changesTxt: changesText, eventsTxt: eventsText });
}
});
});
app.post('/api/changeImp', (req, res) => {
const newImportantText = req.body.newImportantText;
const sql = 'UPDATE site_index SET importants = ?';
connection.query(sql, [newImportantText], (error, results) => {
if (error) {
console.error('Ошибка выполнения SQL-запроса: ' + error);
res.status(500).send('Ошибка при обновлении важного текста в базе данных');
} else {
console.log('Важный текст успешно обновлен в базе данных');
res.json({ message: 'Важный текст успешно обновлен' });
}
});
});
app.post('/api/changeCng', (req, res) => {
const newChangesText = req.body.newChangesText;
const sql = 'UPDATE site_index SET changes = ?';
connection.query(sql, [newChangesText], (error, results) => {
if (error) {
console.error('Ошибка выполнения SQL-запроса: ' + error);
res.status(500).send('Ошибка при обновлении важного текста в базе данных');
} else {
console.log('Важный текст успешно обновлен в базе данных');
res.json({ message: 'Важный текст успешно обновлен' });
}
});
});
app.post('/api/changeEve', (req, res) => {
const newEventsText = req.body.newEventsText;
const sql = 'UPDATE site_index SET events = ?';
connection.query(sql, [newEventsText], (error, results) => {
if (error) {
console.error('Ошибка выполнения SQL-запроса: ' + error);
res.status(500).send('Ошибка при обновлении важного текста в базе данных');
} else {
console.log('Важный текст успешно обновлен в базе данных');
res.json({ message: 'Важный текст успешно обновлен' });
}
});
});
const wss = new ws.WebSocketServer({ port: 3001 });
wss.on('connection', (ws) => {
const id = uuid();
clients[id] = ws;
console.log(`Client connected ${id}`);
ws.send(JSON.stringify(messages));
ws.on('message', (rawMessage) => {
const {name, message} = JSON.parse(rawMessage);
messages.push({name, message});
for (const id in clients) {
client[id].send(JSON.stringify([{name, message}]))
};
});
ws.on('close', () => {
delete clients[id];
console.log(`Client disconnected ${id}`)
})
})
app.listen(conport);
process.on('SIGINT', () => {
wss.close();
fs.writeFile('log', JSON.stringify(messages), err => {
if (err) {
console.log(err);
}
process.exit();
});
})
process.on('SIGTERM', () => {
wss.close();
fs.writeFile('log', JSON.stringify(messages), err => {
if (err) {
console.log(err);
}
process.exit();
});
})
I found this article and tried to solve it, but it failed, I attach the source code unchanged from the article above
New contributor
lovska is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.