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

How can API access be limited according to user type in the correct manner?

Imagine there are two users in the system, named A and B. User A has full access to all resources, while user B has limited access. What is the most effective way to prevent user B from accessing resources that they do not have permission to? Should a w ...

Guide on integrating react-tether with react-dom createPortal for custom styling of tethered components based on their target components

Within a Component, I am rendering buttons each with its own tooltip. The challenge is to make the tooltip appear upon hovering over the button since the tooltip may contain more than just text and cannot be solely created with CSS. The solution involves ...

Angular universal issue: 404 error code failing to function properly

After numerous attempts, I find myself at a dead end. Our Angular 11 website requires Universal for SEO purposes, and we have set up a 404 page to redirect when necessary. The issue arises when the redirect returns a status code of 200 instead of 404. To ...

Storing a reference to children generated by a function within a child prop

I am currently working on a Feed component that accepts a data prop, consisting of an array of items, and a children prop intended for a function that maps the data to a DOM element. My current challenge is implementing the ability to scroll to any elemen ...

The functionality of the jQuery script is not operating optimally, causing the expected alert to not be displayed

I implemented this jQuery script: $('input[name="add-post"]').on('click', function(form) { form.preventDefault(); for ( instance in CKEDITOR.instances ) CKEDITOR.instances[instance].updateElement(); $.ajax({ typ ...

Tips for utilizing onsubmit following an ajax validation check

How can I implement the onsubmit method after an ajax check? The current onsubmit function is not working. $(document).ready(function(){ $("#p_code").change(function(){ $("#message").html("<img src='ajax_loader.gif' width='26 ...

Using jest to mock the .save() function in sequelize

Looking for help to mock the .save() function from sequelize using jest? I encountered an error in my code within user.services.test.js. Can anyone assist me with this issue? The error message states: "result.save() is not a function." user.services.te ...

The angular controller function is failing to set $scope.value

I've been facing an issue with setting an Angular variable value in a controller function that is created by a directive. For some reason, it doesn't seem to work when I try to assign the value within the controller function, even though it displ ...

Modeling a versatile user system in Mongoose for various user types

I am in the process of creating a unique social networking platform for students and teachers using the MEAN stack. Each student will have their own distinct account page separate from the teachers. There is only one registration page where both teachers ...

Hear and register keypress in Angular service

I offer a dialog service Check it out below @Injectable() export class HomeDialogService { public constructor(private readonly dialogService: DialogService, private readonly userAgent: UserAgentService) {} @HostListener('document:keydown.escape ...

The variable in the dataTables JavaScript is not receiving the latest updates

//update function $('#dataTable tbody').on('click', '.am-text-secondary', function() { //extract id from selected row var rowData = table.row($(this).parents('tr')).data(); var updateId = rowData.id; ...

Refresh all color pickers with Bootstrap 4 Colorpicker - enforce the update of every color selector

Currently, I am utilizing the Bootstrap 4 color picker library which can be found at this link: In my code, I have defined color pickers that look like this: <div class="input-group cpicker"> <input type="text" class="form-control input-lg" ...

Looking to fill every space? Try using React with MUI Grid!

I am currently using Material UI Grid to create an image grid, and I am facing challenges in eliminating the gaps between certain grid items. Despite attempting to modify the alignitems and justify values of the container, I have not been successful in r ...

Controller and Directive both setting up isolated scope for a shared element

Having trouble with adding the ng-intro-options attribute to the HTML element. The Issue var App = angular.module('MyApp', ['infinite-scroll', 'angular-intro']); App.controller('MyController', ['$scope', ...

Obtain the name of the checkbox that has been selected

I'm new to JavaScript and HTML, so my question might seem silly to you, but I'm stuck on it. I'm trying to get the name of the selected checkbox. Here's the code I've been working with: <br> <% for(var i = 0; i < ...

Converting a multipart form data string into JSON format

Can you help me figure out how to convert a multipart form data into a JSON object in Node.js? I've been looking for the right module but haven't had any luck so far. Here is an example of my form data: ------WebKitFormBoundaryZfql9GlVvi0vwMml& ...

What causes me to lose my session in one node application when I log into another?

I've encountered an issue where logging into one of my Node.js applications automatically logs me out of another, even though they are running on different ports. Both applications are using Passport for authentication and Express-session for session ...

Firebase User Becomes Undefined Upon Refreshing the Web Page

My situation is quite straightforward. I have developed a Firebase web application and I am logging in with my Google account. The problem arises when I have to keep logging back in every time the page is refreshed, as depicted in these steps: Initialize ...

In what way are these columns altering their layout without the use of JavaScript?

While I was searching for a solution to organize content based on screen size, I came across this website. The layout of the site changes depending on the size of the browser window. When I resize my browser or view the site on a phone, the large image at ...

Combining arrays using Observables in Typescript with RxJS

Having some issues using rxjs Observable.concat function in typescript. Encountering an error "Cannot read property 'apply' of undefined" The problem appears to be limited to typescript and may be related to rxjs version 5 concat. The code seems ...