Experiencing difficulties in updating the Express page

Encountering an issue with page refreshes, I'm struggling to make it work smoothly. The process begins with filling out a form on an HTML page, which then posts to an API on a different service using the Node RequestJS module. After the post, the other service performs certain tasks on its end, and I then make a get request to retrieve the ID of the completed job.

With the obtained ID, I trigger another get request to fetch the logs for the completed job. However, since the logs are still being populated, I need a function to refresh the webpage (which is a simple ExpressJS served page, not actual HTML) until the logs are complete.

The challenge lies in getting the refresh function to actually work.

The code in my main.js file (linked to the HTML page):

request({
    url: 'http://'+host+'/hwChange',
    method: "POST",
    headers: {
        "content-type": "application/json",
    },
    body: jSON
})
setTimeout(function(){
    request({
        url: 'http://'+host+'/lastWF',
        method: "GET",
    })    
}, 1000)
setTimeout(function(){location.href='/log'}, 2000)
timer = 2000
for ( i=0;i<30;i++){
    timer = timer+2000
    setTimeout(function(){
        request({
            url: 'http://'+host+'/log',
            method: "GET"
        })
    },timer)
}

And the code in my ExpressJS (server-side code):

app.post('/hwChange', jsonParser, function (req,res) {
   if (!req.body) return res.sendStatus(500)
   request({
      url: 'https://'+user+':'+pass+'@orcprod.adeo.no:443/vco/api/workflows/9edb9c28-2e71-4d41-a789-f7d94ee4128a/executions',
      method: "POST",
      headers: {
         "content-type": "application/json",
      },
      body: JSON.stringify(req.body)
   }, function (error, response, body){
         console.log(response)
   })
})

app.get('/lastWF', function (req,res){
   request.get('https://'+user+':'+pass+'@orcprod.adeo.no:443/vco/api/workflows/9edb9c28-2e71-4d41-a789-f7d94ee4128a/executions', function (error, response, body){
      if (!error && response.statusCode == 200) {
         //console.log(body)
      }   
      var newest = JSON.parse(body)
      newest = newest.relations.link

      var arr = []
      for (var i = newest.length - 1; i >= 2; i--) {
         var now = newest[i].attributes[1].value
         arr.push(new Date(now))
      }
      var maxDate = new Date(Math.max.apply(null, arr))

      for (var i = newest.length - 1; i >= 2; i--) {
         var now = newest[i].attributes[1].value
         if ( new Date(now).getTime() == maxDate.getTime() ) {
            WFid = newest[i].attributes[0].value
         }
      }
         res.end("<BR><BR>All done!")
   })
})         

app.get('/log', function (req, res) {
   request.get('https://'+user+':'+pass+'@orcprod.adeo.no:443/vco/api/workflows/9edb9c28-2e71-4d41-a789-f7d94ee4128a/executions/'+WFid+'/logs', function (error, response, body){
      if (!error && response.statusCode == 200) {
         //console.log(body)
      }
      var logs = JSON.parse(body)
      for ( i = logs.logs.length -1 ; i>=0; i-- ){ 
         res.write(logs.logs[i].entry["short-description"]+"<BR>")
      }
      res.end("Done "+WFid)
   })
})

Attempts to use location.reload and location = location.href in main.js have been unsuccessful. It seems the refresh is happening too quickly, so I attempted to slow it down with a loop.

In the provided code, I suspect my timed refresh loop is failing due to the location.href just above it.

Any advice or guidance on this issue would be greatly appreciated.

Answer №1

Utilized res.render with JADE to dynamically insert a meta tag in the webpage based on the status of the last received log message. The meta tag is added if the last message has not been received, and removed once it has been received. This implementation successfully updates the page automatically every 2 seconds when accessing /log, until the final log message is received and the updates cease.

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

What is the best way to distribute a function within a div container?

I'm currently working on a function that manages the show/hide functionality and position of tooltips: tooltip = (e) => { // show/hide and position of tooltip // retrieve element data } In addition, I have div elements whe ...

Why am I experiencing a problem with my ajax call only working once when I submit forms that are rendered with @Html.Render

I have a scenario where my index page loads with two partial views, each containing an ajax call that filters content based on date. The issue I'm facing is that the ajax call only works once successfully, and subsequent attempts cause a full page ref ...

Ways to have Express display a randomly selected question from my personal JSON file

I have set up a personal server to enhance my backend coding skills. Currently, it is in its initial phase. I have developed a basic express application where I can import and display a JSON file. However, I am facing a challenge with automatically loading ...

The React application is functioning properly; however, during compilation, it continually displays an error stating that the module cannot be found

Compilation Failed. Error: Module not found, unable to resolve the specified path. webpack compiled with 1 error I was hoping for a successful compilation, but unfortunately encountered an error. It's perplexing as the application is functioning co ...

Converting JSON data from ASP.NET MVC to a Canvas.js chart

Despite my efforts to find a solution by looking through similar posts, I am unable to resolve the issue. Within my asp.net MVC controller, I have a method called public object OfferChart() List<Det> obj = new List<Det>(); foreach ...

Error encountered while attempting to access collection using Firebase credentials

I've been utilizing Node.js with Express for my latest project and everything was running smoothly until I encountered an issue when trying to retrieve a collection using my middleware. Here is the snippet of my middleware: const FBAuth = (req, res, ...

Utilizing Props to Manage State within Child Components

Is it possible to assign the props received from a Parent Component as the state of a Component? export default class SomeComp extends Component { constructor(props) { super(props); this.state = someProps; // <-- I want to set the ...

What could be causing my getAsFile() method to return null?

Below is the code I have been working on: document.getElementById("Image_Panel").addEventListener('paste', (event) => { console.log("Initiating image paste - Step 1"); const clipboardData = event.clipboardData; // Checking ...

Angular UI Bootstrap collapse directive fails to trigger expandDone() function

I am currently utilizing UI Bootstrap for Angular in one of my projects, and I have developed a directive that encapsulates the collapse functionality from UI Bootstrap. Here is how it looks: app.directive( 'arSection', ['$timeout', fu ...

Filter object in Angular to remove empty values

Below are the specific data sets: $scope.icons = [{ "id": 1, "bonuses": [ { "id": 1, "name": "Rob", "amount": 10, "foreman": 1, "percA": 1, "percB": 0 }, { "id": 2, "name": "Mark", "amount": 20, "foreman": 1, "percA": 1, "percB": 0 }, ] }, { ...

What is the best way to use jQuery to toggle the visibility of a <panel>?

My objective is to display a panel with two labels on a button click, but I'm facing issues achieving this functionality. When I click on the button (id=Button1), the panel (id=anspanel) should appear, but it remains hidden even after clicking the but ...

TypeScript application was constructed with incorrect imports from the src folder instead of the dist folder

Summary: App successfully built but importing files from src folder instead of dist I have a TypeScript-powered Express application. This is the configuration of tsconfig.json file: { "compilerOptions": { "target": "es5&quo ...

Eliminate all the zeros from the date string

Trying to work with a string that is in the format '01/02/2016' and my goal is to eliminate the leading zeros so I end up with '1/2/2016' using regex. So far, I have attempted '01/02/2016'.replace(/^0|[^\/]0./, '&ap ...

Unable to launch React Native project

Error: Module Not Found Cannot find module 'C:\Users\Admin\AppData\Local\npm-cache\_npx\7930a8670f922cdb\node_modules\@babel\parser\lib\index.js'. Please make sure that your package.jso ...

In search of grabbing an image from a list item and relocating it to sit before the division tagged with class "event-title"

I am struggling with selecting each list element within the ul and moving the image inside the div class="event-details" above the div with the class="event-title". This adjustment is necessary for achieving the desired styling since the wordpress Event pl ...

How can we minimize the data contained in JSON HTML markup?

https://i.stack.imgur.com/mzuB0.png Currently, I am attempting to find a way to conceal the last 12 digits in the price shown on a button, as it is excessively long. The method I am utilizing involves a JSON api and insertAdjacentHTML markup. This snipp ...

Check the length of a ngRepeat array after the initial filtering before applying limitTo for further refinement

Currently, I am implementing pagination in my Angular application by using a custom startAtIndex filter along with the limitTo filter. My goal is to show the total number of results in the dataset, regardless of the current page. However, due to the use of ...

How come I am unable to save an array of objects in a State within React JS?

React JS component: When I make a request to the backend to fetch data stored in a MySQL table, it returns an array of objects. I store this data in a state called `favcoin`. However, when I console.log(favcoin), it displays an empty array [ ]. Strangely, ...

Calculating JS functions before images are loaded

Following up on a previous question, I am utilizing JavaScript code from another article to position a "content" div relative to a fixed div in my project. However, the issue arises when the positioning of the "content" div is calculated only after all the ...

Performing JSON data extraction and conversion using JavaScript

Hello! I'm working with a script that converts data into an array, but I want to enhance it so that I can extract and convert data for each object (arb, astar, aurora, avax, baba, bsc, etc.), as shown in the screenshot. Here is the current script tha ...