Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

205
Vistas
Express.js: How to refresh on DB change in backend?

I decided to make a janky chat site type thing to get me started working with requests and such.

My approach was to create an express.js server that takes in requests when the '/messageReciever' is posted to.

app.post("/messageReciever", (req, res) => {
        logMessage(req.body.message);
});

The next step was to make a 'client' that could send information to this end point:

var XMLHttpRequest = require("XMLHttpRequest").XMLHttpRequest;

function makePostRequest(url, json)
{
        let http = new XMLHttpRequest();
        http.open("POST", url, true);
        http.setRequestHeader("Content-Type", "application/json");
        http.send(JSON.stringify(json));
}

function sendMessage(url, message)
{
    makePostRequest(url, {message: message});
    logMessage(message);
}

Both of these are fine. The issue I'm running into is, once I receive the post request I want to refresh the main page of my site (to show the messages)

app.get('/', (req, res) => {
        res.render('index', data = retrieveMessages());
});

I've tried basically everything I've found online:

res.redirect('back');
res.redirect(req.get('referer'));
res.redirect(req.originalUrl)

I used res.redirect('back') previously in my code, and it works. The issue is that I'm trying to refresh someone's connection to a site based on someone else's connection; meaning I can't use the response information like I normally could.

I've tried looking for ways to refresh pages from outside functions but I can't find anything.

(I realize that there are easier ways to make a chat site that don't include weirdly sending data back and forth between two server's)

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

You can use a package called socket.io. Socket.io allows you to send requests to a client once the server has some data.

Example:

Server:

// Define express
const express = require('express');
const app = express();
// Create the server
const http = require('http');
const server = http.createServer(app);
// Define socket.io
const io = require('socket.io')(server);
// Define the port for the server to listen on
let port = 3000;

function logMessage(message, id) {
    ...
    io.emit('message_sent_' + id, { message }); // Emit that a message was sent to the clients
}
function recieveMessages(id) {
    // Get the messages somehow
}

app.post('/messageReciever', (req, res) => {
    // req.body.message is your message and req.cookies.id is the clients random ID
    logMessage(req.body.message, req.cookies.id);
});

app.get('/', (req, res) => {
    res.cookie('id', 'some-generated-id'); // Set a cookie for the unique ID to fetch user messages
    res.render('index', { data: retrieveMessages() });
});

// Get the server listening to incoming requests
server.listen(port, () => console.log('my app is online');

Client:

<!doctype html>
<html>
<body>
    ...
</body>
<script src="/socket.io/socket.io.js"></script>
<script>
    const socket = io.connect();
    socket.on('message_sent_' + 'some-id', function(data) {
        // Do something with the data
    });
</script>
</html>

References:

  • https://socket.io/docs/v4/
  • http://expressjs.com/
  • https://marques-robinson-project.medium.com/chat-app-with-socket-io-and-express-using-node-js-2293b87f47c3
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda