Incorporating fresh data from a node.js backend to refresh a webpage section

I'm currently working on creating an app that can retrieve the song a user is currently listening to using a web scraper. While I've managed to direct users to the page and display the current song title, they must manually refresh the entire page if the song changes. I'm exploring options to execute the code in the routes file to dynamically update the song data on the page without requiring a full refresh.

Desired functionality:

  1. User initiates a GET request to /songinfo endpoint.
  2. The app scrapes the latest song information from an external source.
  3. The app renders the EJS file with the updated song data.
  4. A timer triggers or the user manually initiates a refresh action.
  5. Only the song data section of the page updates with the new information while the rest of the content remains unaffected.

Thank you for your help!

Answer №1

To optimize your code, consider utilizing ajax for efficiency.

An effective method is to establish a new route on your nodejs server that delivers song data as json instead of rendering an EJS file to the client.

If your current code looks like this:

app.get('/songinfo', function(req, res) {
  request.get('http://songinfo.com/songs', function(err, res, data) {
    res.render('songinfo.ejs', data);
  });
});

You can modify it to this approach:

function getSongInfo(callback) {
  request.get('http://songinfo.com/songs', function(err, res, data) {
    callback(data);
  });
}

app.get('/songinfo', function(req, res) {
  getSongInfo(function(data) {
    res.render('songinfo.ejs', data);
  });
});

app.get('/raw-songinfo', function(req, res) {
  getSongInfo(function(data) {
    res.setHeader('content-type', 'application/json');
    res.send(data);
  });
});

This restructuring extracts the getSongInfo logic to maintain a DRY application and introduces a second route that utilizes the same function. This time, instead of returning data in an ejs file, it sends back json. To incorporate this change into your ejs file, you can implement the following logic:

<button onclick='reloadData()'> Reload me! </button>
<script type='text/javascript'> 
  function reloadData() {
    var xmlhttp = new XMLHttpRequest();
    xmlhttp.onreadystatechange = function() {
      if (xmlhttp.readyState == XMLHttpRequest.DONE ) {
        if(xmlhttp.status == 200){
          // Update the data in your app somehow...
          // example:
          var responseData = JSON.parse(xmlhttp.responseText);
          document.getElementById('songs-count').innerHTML = responseData.length;
        } else {
          alert('something went wrong!');
        }
      }
    }
</script>

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 Serverless Function on Vercel has exceeded its time limit and timed out

After deploying my Express.js server using Vercel's serverless service, I encountered a recurring issue where every time I tried to use an endpoint, an error message saying 'This Serverless Function has timed out' appeared. Despite watching ...

How Meteor Handles HTTP Requests in its package.js File

When accessing data from an external source at autopublish.meteor.com, our goal is to gather information about a package's latest release tag either from GitHub or the NPM registry: var version; try { var packageJson = JSON.parse(Npm.require(' ...

Challenges with Expanding Memory for Puppeteer

I am currently using a Puppeteer script on both my Amazon Linux EC2 Instance and my Macbook Air (OSX). The script needs to remain active on a single page and repeatedly perform form-filling tasks regularly. However, I have encountered an issue where runni ...

What is the best way to eliminate excess spacing between HTML td and table elements in Outlook?

Here's the HTML email code snippet. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Co ...

Is there a way to prevent text from being automatically linked after using an <a> tag?

Whenever I attempt to input text into the div tag below, it mysteriously appears hyperlinked, even though there is no "a" tag enclosing it. HTML: <html> <head> <link href = "https://fonts.googleleapis.com/css?family=Work+Sans:3 ...

Is it better to upload images to Vue.js (front end) or Node.js (back end) when using Vue.js and Node.js together?

Looking to create an image upload component that saves the uploaded image name to a database. Uncertain of where to upload the image itself. Should I store it in uploads/ within vue.js, or send the whole image to the backend node.js and store it there? ...

"Encountering a glitch with the $npm server startup

Every time I try to start a server for a web application, I keep encountering an error. All I'm doing is entering "npm run server" in the terminal from the main directory of the folder, but I get an error message saying ./node_modules/http-server/bin ...

Unable to adjust iframe height

Below is a snippet of code that I am working with: <style type="text/css"> .div_class { position:absolute; border:1px solid blue; left:50%; margin-left:-375px; margin-top:100px; height:300px; width:500px; overflow:hidden; } .iframe_class { position: ...

Conceal a Component within an Embedded Frame

Hey there! I've been attempting to hide a header within an iframe, but it seems like my code isn't doing the trick. Could someone take a look and help me diagnose why the header is still visible? Thanks in advance! <iframe id="booking_iframe" ...

Selenium was unable to find the p tag element on the webpage

I apologize for reaching out to you all for assistance with such a basic task, but I have tried everything in my toolkit and still can't seem to figure it out. I've experimented with partial xpath, full xpath, and various CSS selectors. I am see ...

Adjusting the inner div dimensions to be 100% of the body's size without relying on the parent div using JavaScript

I have a main layer with multiple layers stacked on top of it. I need the second layer to extend its width to match the body's width. Main Project: http://example.com What I've tried: I looked into: Solution for matching div width with body ...

Can you confirm if the content-type of this SOAP response is valid?

While trying to utilize a third-party WebService within Visual Studio 2008, I received a unique response from the server. This particular response contained two content-type tags. HTTP/1.0 200 OK Server: SMBDK_1/2.3.0 Date: Thu, 09 Aug 2012 18:59:14 G ...

Closing the space between navigation bar choices

I'm currently working on my website's navbar menu and struggling to eliminate the gap between each of the navbar links. It seems that the li attributes with the class dropdown are slightly wider than the rest of the links, causing this issue. I&a ...

Error encountered: "npm install command failed due to cb() not being called."

Having previously worked on a react-native project on one computer, I now want to continue working on the same project folder on a different Linux machine. The project folder does not contain a node_modules directory, but it does have a "package.json" fil ...

An error occurred while processing the JSReport request

I am encountering an issue while trying to utilize the jsreport API for rendering a report template. The error I am facing is as follows: { body: "{"body":"\"{\\\"template\\\":{\\\"shortid\\& ...

OAuth: Once authenticated, utilize the access token via various pathways

Can someone please help me understand OAuth flows? I'm using the Spotify API with passportjs for user authentication. However, I'm confused about how to make API calls from my app after the user is authenticated. If you want to take a look at my ...

Applying CSS styles to a page depending on certain conditions

Currently, I have a page in SharePoint that can function as a pop-up. I am using JavaScript to identify whether it is a pop-up by checking if window.location.search.match("[?&]IsDlg=1"). However, I am struggling to figure out how to insert CSS based on ...

What is the process for transforming a Typescript source file into JavaScript?

I have a basic HTML file with a script source set to index.ts. index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge ...

The VueJS front-end is left waiting for a response from the NodeJS backend that never

Having some trouble setting up a login feature in my web application. The backend is using a MongoDB database and NodeJS (express), while the front-end uses VueJS. However, I'm facing an issue where the response from the backend isn't reaching th ...

Utilizing the powerful combination of TailwindCSS and Next.js Image to achieve a full height display with

Trying to utilize the Next.js' <Image> component with the layout=fill setting, I created a relative div housing the Image tag. However, I am looking for a way to set the height based on the Image's height. Came across this example, but the ...