I am making a server with NodeJS and Express, but when I make a get request to the basic route (‘http://localhost:3000/’) nothing happens, the request stays waiting. I have reviewed my code many times but I can’t find what could be failing. How can I solve it?
PD: I’m also implementing socket.io
This is my code:
const express = require("express");
const axios = require("axios");
const cors = require('cors');
const app = express();
const { createClient } = require('redis');
const http = require('http');
const server = http.createServer(app);
const { Server } = require("socket.io");
const db = require('./helper/db')
const io = new Server(server, {
cors: {
origin: "*"
}
});
app.use(express.json());
app.use(cors);
app.use(express.urlencoded({
extended: true
}))
app.get("https://stackoverflow.com/", (req,res) => {
res.send('Backend NodeJS SO1 Proyecto2');
});
var claves = [];
var total_registros = 0;
var semestre_cursos = [];
async function consultarRedis() {
const client = await createClient({
url: 'redis://172.17.0.3:6379'
})
.on('error', err => console.log('Redis Client Error', err))
.connect();
total_registros = await client.get('total_registros');
console.log(total_registros)
}
async function consultarRedisSemestre() {
semestre_cursos = [];
const client = await createClient({
url: 'redis://172.17.0.3:6379'
})
.on('error', err => console.log('Redis Client Error', err))
.connect();
var temp = 0;
for(var clave of claves){
try{
temp = await client.hGet('cursos_semestres', clave)
semestre_cursos.push(parseInt(temp))
}catch(error){
console.error(`Error al consultar Redis para la clave "${clave}":`, error)
}
}
}
io.on('connection', (socket) => {
console.log('Cliente conectado');
const interval = setInterval(() => {
consultarRedis();
socket.emit('total_registros', total_registros);
}, 1000);
// Manejar desconexiones de socket.io
socket.on('disconnect', () => {
clearInterval(interval);
console.log('Cliente desconectado');
});
socket.on('selectedSemester', (semestreSeleccionado) => {
claves = [];
claves.push(`SO1:${semestreSeleccionado}`)
claves.push(`BD1:${semestreSeleccionado}`)
claves.push(`LFP:${semestreSeleccionado}`)
claves.push(`SA:${semestreSeleccionado}`)
claves.push(`AYD1:${semestreSeleccionado}`)
const interval = setInterval(async () => {
temp = await consultarRedisSemestre();
socket.emit('valores_semestre', semestre_cursos);
}, 1000);
});
});
server.listen(3000, () => {
console.log("Server on port 3000");
});
Replace app.use(cors);
with app.use(cors());
Best practices:-
- Always declare your variables with let or const to ensure proper scoping.
- Hardcoding Redis server URLs and other configuration values may not be the good for production applications. Consider using environment variables to handle such settings dynamically.