Updating the Backend Automatically in Express.js When the Database Changes

I decided to create a chat platform from scratch to dive into the world of requests and server-side logic.

My strategy involved setting up an express.js server that listens for POST requests to '/messageReceiver'.

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

Next, I developed a 'client' capable of sending data to this designated endpoint:

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);
}

All seems well so far. However, my current challenge is figuring out how to refresh the main page upon receiving a post request in order to display the latest messages.

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

I've experimented with various methods found online, such as:

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

While res.redirect('back') worked before, my predicament lies in refreshing a visitor's connection based on another user's actions without direct access to their response object. It's proven challenging to find a solution for reloading pages externally.

(I acknowledge there are simpler ways to build a chat site rather than engaging in back-and-forth data exchanges between servers)

Answer №1

If you're looking to establish real-time communication between a server and client, consider utilizing the socket.io package. With Socket.io, you can conveniently send requests from the server to the client once there's data available.

Here's an example to guide you:

Server Side:

// Setting up express
const express = require('express');
const app = express();
// Creating the server
const http = require('http');
const server = http.createServer(app);
// Implementing socket.io
const io = require('socket.io')(server);
// Specifying the port for server listening
let port = 3000;

function logMessage(message, id) {
    ...
    io.emit('message_sent_' + id, { message }); // Notifying clients about the message sent
}
function receiveMessages(id) {
    // Retrieving messages
}

app.post('/messageReceiver', (req, res) => {
    // req.body.message contains the message while req.cookies.id represents the client's random ID
    logMessage(req.body.message, req.cookies.id);
});

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

// Configuring the server to listen for incoming requests
server.listen(port, () => console.log('My app is online');

Client Side:

<!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) {
        // Processing the received data
    });
</script>
</html>

For further information, you may refer to the following resources:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

At times, AngularJs template tags fail to evaluate

Can anyone explain why the templating tag [[ opt.option ]] is not always evaluating to a value in this code snippet? <span ng-repeat="opt in options"> <button ng-click="button = [[ opt.option ]]" ng-class="{ active : button == [[ opt.option ]] ...

How can you convert all nodes of a nested JSON tree into class instances in Angular 2 using Typescript?

I have a Leaf class that I want to use to convert all nodes in a JSON response into instances of Leaf. The structure of the JSON response is as follows: JSON Response { "name":"animal", "state":false, "children":[ { "name" ...

Executing the event handler only once

In my React project, I have a button that toggles a boolean state. However, I realized that the button can both set and unset the state due to its toggle functionality. I only want the state to be changed once. Is there a different function I can use ins ...

Do all variables need to be converted into objects in order to be executed in JavaScript?

I'm curious about the idea that primitive data types, like strings, can have properties such as .includes. Does this mean that all primitive data types are transformed into objects before they are executed? If so, what is the reasoning behind maintain ...

Is there a way to dynamically change the helperText of a Material UI TextField using its current value through code?

I'm currently attempting to dynamically change the helperText of a Material UI TextField based on the value entered into the field. Below is my current implementation: const defaultScores = { STR: 10, DEX: 10, CON: 10, INT: 10, WIS: 10, CH ...

Unable to establish headers once they have been issued - routing error

I have come across various solutions for this problem, but I am struggling to resolve it on my own. Therefore, I am sharing my code here in hopes of receiving assistance. I am new to this and would appreciate any help in understanding and fixing the issue ...

Transmit the Selected Options from the Checkbox Categories

Here's an intriguing situation for you. I've got a webpage that dynamically generates groups of checkboxes, and their names are unknown until they're created. These groups could be named anything from "type" to "profile", and there's a ...

Create an array mapping of locations and convert each location to its corresponding language

With Next.js, I have successfully retrieved the current locale and all available locales for a language selection menu: const {currentLocale, availableLocales} = useContext(LangContext); // currentLocale = "en-US" // availableLocales = ["en- ...

Discover the most effective method for identifying duplicate items within an array

I'm currently working with angular4 and facing a challenge of displaying a list containing only unique values. Whenever I access an API, it returns an array from which I have to filter out repeated data. The API will be accessed periodically, and the ...

Utilizing socket.io effectively for production environments with the power of node.js and react

Greetings, I am currently in the process of setting up my very first socket.io chat application for production. To host the front end, I am utilizing Netlify along with React, and for the backend, I have opted for Heroku with JAWSdb for MySQL. Below is the ...

Ways to update a component when the value of a Promise is altered

I am struggling with Vue component re-rendering due to a problem related to consuming data from a Promise. The data is fetched and stored under the specific property chain (visualData.layout.cube...), where I assign values to DATA properties (such as label ...

Issue found: React-Redux action is not being dispatched

I'm currently working on setting up Google authentication in my React Next.js application. The process involves sending the access token to my backend, where it is validated before a new token is returned in the header for accessing protected resource ...

The Jest testing suites did not successfully pass all the tests

There seems to be an issue when running all tests simultaneously, as the number of failed test suites varies each time. However, running failed test suites individually results in successful tests. Upon examining the stack trace, it appears that the error ...

Discrepancy in performance levels between vector<bool> and array

Recently, I tackled a challenging coding problem in C++ that involved counting prime numbers less than a non-negative number n. My initial solution looked like this: int countPrimes(int n) { vector<bool> flag(n+1,1); for(int i =2;i<n;i++ ...

Using Blob to save CSV file on Safari

Here are the codes I am using to generate a download link for users to download a .csv file from my website. var link = document.createElement("a"); link.id = "csvDwnLink"; window.URL = window.URL || window.webkitURL; var csv = "\ufeff" + CSV, b ...

Converting complex mongodb data structures into Backbone.js Models/Collections

Within my mongodb database, I store collections comprising of documents and embedded documents at the posts and comments levels. One example is a post document that includes two comments as embedded documents. { "__v" : 0, "_id" : ObjectId("502d7b ...

The response is dispatched without delay and does not necessitate awaiting

I am facing an issue with waiting for the completion of the getAllData function before proceeding further. let _partnerToken; async function getAllData(dealerId,id){ let partnerToken; var options = { 'method': 'GET', ' ...

Unable to properly cancel a post request using abort functionality

In the process of building a Next.js app, I encountered an issue with calling a post request. I included a cancel button to halt the post request, and attempted to use abortController in conjunction with Axios (v1.4.0) to achieve this. Even though the &ap ...

Preserve the original position of the inner <div> when animating the container <div> using JQuery

I am currently working on a small website and encountering some challenges with jQuery animation. My issue involves placing a single character text inside a circle and wanting it to grow when the user hovers over it, while keeping the inner text in its ori ...

Tips for transferring a column in an array to an object field within an array

I have a piece of code where I need to pass values from the 'dataList' array into this.data object's 'labels' and 'datasets'-> data. When I try to directly set the values, I get an undefined result. So I created a var ...