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)