Is it possible to view newly added text in real-time on a separate client in Node.js without relying on socket.io?

I am in the process of creating a straightforward web application where users can input phrases. The app works fine, except for one issue - it doesn't display new additions from other users instantly. I am aware that socket.io could solve this problem, but I am exploring other options to keep the site as minimalistic as possible. Below is the code snippet:

//script.js file
fetch('https://server.jonaso1.repl.co/').then(response => response.json())
.then(data => {
   for (let i = 0; i < data.length; i++)
   prependPhrase(data[i]);
 }); //loads saved content onto the page upon access

form.onsubmit = (e) => { //posts input values to server (variable declarations omitted)
  e.preventDefault();
  var data = {
  [input.name1]:input1.value,
  [input2.name]:input2.value,
  [input3.name]:input3.value,
  };

  prependPhrase(data);

  fetch('https://server.jonaso1.repl.co/frases', {
    method: "POST",
    body: JSON.stringify(data),
    headers: {"Content-type": "application/json"}
    })
  };

function prependPhrase(data) {//function to display text on site
  const p = document.createElement('p');
  const span = document.createElement('span');
  p.setAttribute('class', 'p');
  container.prepend(p);
  p.append(`${data.user} sent : `)
  p.append(span);
  span.append(`${data.frasefavorita}`)
  p.append(` - ${data.autor}`)
}

//server.js file
mongoose.connect(mongoDB).then(() => console.log('database connected')).catch((err) => console.log(err));

app.use(cors());
app.use(express.urlencoded({extended:true}));
app.use(express.json());


app.get('/', (req, res) => {
  phrase.find().then(result => {//responds to GET requests with MongoDB data
    res.send(JSON.stringify(result))
    })
  });

app.post('/frases', (req, res) => { //saves additional phrases in MongoDB
  const frase = new phrase(req.body);
  frase.save().then(() => console.log('phrase saved'));  
  });

app.listen(3000, () => {
console.log('listening on port 3000')});

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

The error message for validating my form magically disappears

I've been working on creating a registration form using HTML, Bootstrap, and JavaScript. My goal was to display an error message when a field is left empty, but for some reason, the error message appears briefly and disappears afterwards. I can't ...

What are some potential problems that could arise when making a POST request for signing authentication in a MERN stack using JWT?

I'm currently in the process of developing a social media application using the MERN stack. To ensure the functionality of the backend API, I am utilizing POSTMAN. Here is an overview of the dependencies outlined in the package.json file: { "na ...

How can you identify dynamically created elements within an AngularJS directive?

I have a directive where I need to target specific DOM elements, some of which are dynamically generated in an ng-repeat loop. If I try to select them directly, I only get the static elements. However, if I delay the selection by, let's say, 500ms, I ...

socket.io initialization and finalization events

Currently, I am integrating socket.io with express 3 for my application development. I am interested in implementing loader animations that will appear when a message is incoming and disappear once the message has been received. Similar to how jQuery&apos ...

Encountering a problem with lazy loading of module routing paths. Issue arises when attempting to navigate to http://localhost:4200

AppLazyLoadingMoudle import {NgModule} from '@angular/core'; import {RouterModule, Routes} from '@angular/router'; const ROUTES : Routes = [ /* ProductModule (defined in the feature module) is loaded lazily when navigating ...

In a React app, there are instances where `localstorage.getitem('key')` may result in returning null

I've encountered a strange issue while building a login form that sets a JWT token in localstorage. The problem arises when, despite being able to see the token in my console.log, setting localstorage.getitem('idToken') sometimes returns nul ...

Retrieve the XML document and substitute any occurrences of ampersands "&" with the word "and" within it

The XML file is not being read by the browser due to the presence of ampersands represented as "&". To resolve this, I am looking to retrieve the XML file and replace all instances of "&" with "and". Is this achievable? Despite attempting to use t ...

What could be causing my array to be misconverted into JSONP data?

let defaultPosts = new Array([]); defaultPosts[0] = "first post"; defaultPosts[1] = "second post"; defaultPosts[2] = "third post"; The array in the console is showing ["first post", "second post", "third post"]; let jsonString = JSON.stringi ...

Samsung Galaxy S7 can interpret alphabetical parameters as numbers in a link sent via SMS

When trying to open a text message with a new message on my website using a link, I encountered an issue specifically with the Galaxy S7. The following code works on most Android phones: sms:5555555555?body=JOIN However, on the Galaxy S7, the "?body=JOIN ...

What is the process for retrieving all documents with negative values for a specific user using Express.js and MongoDB?

My MongoDB database contains all user data as shown below: [ { "user_id": "1", "name": "aaaa", "value": -10 }, { "user_id": "2", "name": "bbbb", "value": 30 }, { , "user_id": "1", "name": "aaaa", "value": 310 ...

When I try to execute `npm start` on Ubuntu 16.04, I encounter npm errors

My Ubuntu 16.04 OS has node v7.10.1 and npm v4.2.0 installed. I encountered an error when trying to start npm or sudo start npm. Everything was working fine this morning, but now I'm getting errors. Can someone please help me troubleshoot this? npm E ...

Dealing with the 404 error for a missing resource in ocLazyLoad

I am seeking guidance on how to handle resource loading errors in ocLazyLoading. I have attempted to load some resources within the resolve section of my $stateProvider. One file, ctrl.js, loads successfully. However, another file, iam-not-there.js, fails ...

What is the purpose of using the variable "header_row || 1" in App Script?

Recently, I stumbled upon a spreadsheet that contains app script for gathering keys of data requested through doGet. In the code, there is a line that reads like this: var headRow = e.parameter.header_row || 1; What exactly does this line mean? I searc ...

What causes CSS files to update automatically in an ExpressJS and NodeJS configuration?

I'm in the process of building a web application using NodeJS, ExpressJS, and Jade. In my project, I have a style.css file that is included like this. This is how my layout.jade looks: doctype html html head title= title link(rel='st ...

Resizing columns in HTML table remains effective even after the page is refreshed

I've created HTML pages with tables that have multiple columns, but I'm experiencing an issue. The columns are not resizable until I refresh the page. Could someone assist me in fixing this problem and explaining why it's happening? ...

Troubleshooting problem with callback functions in Nodejs, Express, and MySQL

I'm struggling to grasp the concept of callbacks and their behavior. When using them, I encountered unexpected results in my code. Even after attempting to utilize the async library, I still couldn't achieve the desired outcome. module.exports.l ...

Classify the JavaScript objects according to the array of object lists

Struggling to find a solution for converting this list of objects based on the group array. The challenge lies in iterating through the group Array and applying the object to multiple places when there are several groups. Additionally, trying to disregard ...

How can I use AJAX to transmit a 2D array to a PHP page and then display each dimension individually?

Recently, I created a webpage with multiple checkboxes. Using jQuery, I am able to fetch data from these checkboxes and store them in a two-dimensional array. Here is an excerpt of my code: HTML snippet: <input type="checkbox" name="checkboxs[]" pric ...

Error: The Service Fabric node.js guest application running an express.js server is encountering an EADDRIN

Uncertain whether this issue stems from Service Fabric or is related to node.js. The problem I'm facing can be found here. Upon initially deploying the node.js application, it runs smoothly. However, upon redeployment, the application fails to functi ...

Comparing NextJs hydration with using the client-side approach

Currently exploring the ins and outs of NextJs to grasp its fundamental features. It is my understanding that by default, NextJs components operate on the server-side and utilize Hydration to enable interactivity shortly after displaying pre-rendered HTML ...