Analyzing the HTTP status codes of various websites

This particular element is designed to fetch and display the HTTP status code for various websites using data from a file called data.json. Currently, all sites are shown as "Live" even though the second site does not exist and should ideally display statuses like "404", "503" or "523". The HTTP status code 200 indicates that the site is "Live". The goal here is to show different messages based on each status code received in the response.

ExampleComponent.vue

<template>
  <div class="container">
    <table class="table table-stripped table-hover" id="cont-table">
      <thead>
        <tr>
          <th>URL</th>
          <th>Status</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(site, index) in sites" :key="index">
          <td><a v-bind:href="getHref(site)" target="_blank">{{ site.url }}</a></td>
          <td v-if="site.status = 200"><span class="label label-success">Live</span>
          <td v-else-if="site.status = 404"><span class="label label-success">404</span></td>
          <td v-else-if="site.status = 503"><span class="label label-success">503</span></td>
          <td v-else-if="site.status = 523"><span class="label label-success">523</span></td>
        </tr>
      </tbody>
    </table>

  </div>
</template>

<script>
export default {
  data() {
    return {
      siteDataUrl: "./data.json",
      sites: []
    }
  },

  created: function () {
    this.loadData();
  },

  methods: {
    getHref: function (site) {
      if (!site.port) site.port = 80;
      return `https://${site.url}:${site.port}`;
    },

    loadData: function () {
      let self = this
      fetch(this.siteDataUrl)
          .then(r => r.json())
          .then((resp) => {
              self.sites = resp
              self.getStatus();
          });
    },

    getStatus: function () {
      let self = this;
      self.sites.forEach(function (site, index) {
          let url = `https://${site.url}`;
          if (site.port && site.port != 80 && site.port != 443) url += `:${site.port}`;

          fetch(url, { mode: 'no-cors'})
              .then((resp) => {
                  site.status = false;

                  if (resp.status == 200) site.status = 200;
                  if (resp.status == 404) site.status = 404;
                  if (resp.status == 503) site.status = 503;
                  if (resp.status == 523) site.status = 523;

                  self.$set(self.sites, index, site);
              })
      })
    }
  }
}
</script>

data.json

[
  {
    "name": "",
    "url": "www.google.com",
    "port": 80
  },
  {
    "name": "",
    "url": "www.foo.com",
    "port": 443
  }
]

Answer №1

The issue likely lies within the conditions specified for v-if and v-else-if. It appears that an assignment operator (=) is being mistakenly used instead of an equality operator (==).

The current implementation sets site.status to a non-zero value before evaluating the result. The first expression results in 200, causing it to always be true and rendering Live.

<td v-if="site.status = 200"><span class="label label-success">Live</span>
<td v-else-if="site.status = 404"><span class="label label-success">404</span></td>
<td v-else-if="site.status = 503"><span class="label label-success">503</span></td>
<td v-else-if="site.status = 523"><span class="label label-success">523</span></td>

To fix this, use the correct equality operators == or ===:

<td v-if="site.status == 200"><span class="label label-success">Live</span>
<td v-else-if="site.status == 404"><span class="label label-success">404</span></td>
<td v-else-if="site.status == 503"><span class="label label-success">503</span></td>
<td v-else-if="site.status == 523"><span class="label label-success">523</span></td>

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

Unexpected appearance of a blue line in Material UI when the overflow attribute is included

For my React application, I've integrated Material-UI along with styled components. The strange thing is that when I use a Chrome browser to view the app, I encounter an issue that doesn't seem to happen in Firefox. The problem arises when I add ...

Here is a helpful guide on updating dropdown values in real time by retrieving data from an SQL database

This feature allows users to select a package category from a dropdown menu. For example, selecting "Unifi" will display only Unifi packages, while selecting "Streamyx" will show only Streamyx packages. However, if I first select Unifi and then change to S ...

Determining in Express.js whether headers have been sent or not

As I develop a library that involves setting headers, I aim to provide a personalized error message in case the headers have already been sent. Rather than simply letting it fail with the default "Can't set headers after they are sent" message from No ...

Merge a pair of observables to create a single combined output

Hey there, I'm currently diving into the world of RxJS and reactive programming. One challenge I'm facing is merging two observables. The first observable contains an array of objects called DefectImages[], while the second observable holds an ar ...

JS, Async (library), Express. Issue with response() function not functioning properly within an async context

After completing some asynchronous operations using Async.waterfall([], cb), I attempted to call res(). Unfortunately, it appears that the req/res objects are not accessible in that scope. Instead, I have to call them from my callback function cb. functio ...

Elements are randomly glitching out with CSS transitions in Firefox

Chrome is working perfectly for me, but when I switch to Firefox it behaves differently than expected I am attempting to create a simple animation (utilizing transitions) that continuously runs on mouseover and smoothly returns to the starting position on ...

How can I parse a JSON string in a node.js environment?

My current challenge involves sending a JSON string and parsing it on the server-side in node js. The specific value I am trying to extract is the title, but I keep encountering undefined when attempting to parse it. This is my current approach: Home.ejs ...

How to Properly Implement app.use() in Express for Middleware

What is the reason behind some middleware functions being passed in with invocation parentheses, while an anonymous function is passed in without being invoked? app.use(logger()); app.use(bodyParser()); If logger() is evaluated immediately and the return ...

Creating a Blurry Image Effect in Vue.js

Check out this example using Next.js: <Image blurDataURL="/poster.png" src={item.cover_path || defaultImage} alt={item.name} layout="fill" className="next-image" placeholder="[blur][1]" /> Now, how can I ...

Javascript code not running as expected

Check out this code snippet: function generateRandomTeams() { const prom = new Promise(() => { // ... console.log('teams', props.state.teams) // logs }) .then(() => { console.log('here') // doesn't log }) ...

Error encountered: EPERM - Unable to perform operation on Windows system

Recently, I executed the following command: npm config set prefix /usr/local After executing this command, I encountered an issue when attempting to run any npm commands on Windows OS. The error message displayed was as follows: Error: EPERM: operation ...

Customize the duration of Skeleton animations in Material UI

The <Skeleton> components in mui utilize pulse or wavy animations. Wondering if there's a method to quicken this animation, perhaps by adjusting the duration? ...

Can you explain the inner workings of the provided code in a step-by-step manner?

I stumbled upon this code snippet that checks if the number of occurrences of an element in an array is greater than a specified value, and if so, it will remove the number: function deleteNth(arr,x) { var cache = {}; return arr.filter(function(n) { ...

Charting Add-Ons for jQuery

Looking for suggestions on user-friendly graph drawing plugins compatible with jQuery. Currently developing a web application that will retrieve data from a remote database and present it through visual graphs... Explored jgcharts (the jQuery Google Chart ...

Is my Magento journey on the correct course?

I am wanting to include or require a file in DATA.php within magento. Below is the code snippet I have: public function formatPrice($price) { require_once(Mage::getBaseDir('app').'\design\frontend\neighborhood ...

Determining the visible dimensions of an iframe

Is there a way to determine the visual size inside an iframe using JavaScript or jQuery? In this scenario, only a portion of the iframe is displayed. The iframe itself has dimensions of 300x300, but it is being limited by a div to 300x100. <div style= ...

Combining PHP code within JavaScript nested inside PHP code

I am currently facing an issue with my PHP while loop. The loop is supposed to iterate through a file, extract three variables for every three lines, and then use those variables to create markers using JavaScript. However, when I try to pass the PHP varia ...

Editable content <div>: Cursor position begins prior to the placeholder

Having an issue with a contenteditable div where the placeholder text starts behind the cursor instead of at the cursor position. Any suggestions on how to correct this? <div id="input_box" contenteditable="true" autofocus="autofocus" autocomplete="o ...

Jquery deactivates the CSS hover effect

Having a dilemma with linked photos on my website. I have set their opacity to 0.45 by default, but want them to change to full opacity (1) when hovered over or clicked. I've implemented a JQuery function that resets the rest of the photos back to 0.4 ...

To show the image along with the .titleclass, .subtitleclass, and .description when clicking on it, what steps do I

<?php while($galleryrec = mysqli_fetch_array($getresultgallery)){ ?> <div class="col-lg-2 col-md-2 mb-4 mb-lg-0" id="imageidback"> <img data-id ="<?php echo $galleryrec['publishid& ...