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

Creating a JavaScript function to automatically hide a dropdown menu after a specific duration

I'm currently working on a side menu that drops down when hovering over Section One within the <a> tag. I need some guidance on how to make the JavaScript code continuously check the state of the list after a set amount of time in order to autom ...

Utilizing Angular 6 and JavaScript to invoke two functions within an (ngClick) event in both the Component and JavaScript

I have a requirement to execute two functions in my click event, one for my component and the other for a custom JavaScript function. Here is the code snippet: Angular click event: <button type="button" class="btn btn-primary" (click)="Plans(); " [att ...

What steps do I need to take in order to create functions that are

I have 10 functions with similar structures: function socialMedia_ajax(media){ return ajaxRequest('search/' + media + 'id', media + 'id').then( function(res) { var imgStatus = res[1].length > 0 ? "c ...

The error message "Unable to execute stripe.customers.createBalanceTransaction function" is displayed on

Having trouble with a Type Error while attempting to use stripe's createBalanceTransaction function. You can find the API reference for the function here: https://stripe.com/docs/api/customer_balance_transactions/create The error message being receiv ...

Implementing an onclick event listener in combination with an AJAX API call

I'm really struggling with this issue. Here's the problem I'm facing: I have a text area, and I need to be able to click on a button to perform two tasks: Convert the address text into uppercase Loop through the data retrieved from an API ...

Avoid navigating through hidden tab indexes

Below is the HTML code that I am working with: <span tabindex="19"> </span> <span tabindex="20"> </span> <span tabindex="21"> </span> <span id="hidden" tabindex="22"> </span> <span tabindex="23"&g ...

AngularJS and adding to an array in the routing process

I'm currently working on creating a contact list with two different views. One view displays all the contacts and includes an option to add a new contact, which is represented by a button rather than a space to input information directly. The other vi ...

Ensuring Stringency in JQuery's '$' Selector

I have a specific data attribute within the div element that is displayed in the HTML. <div my-custom-attrib="1".../> <div my-custom-sttrib="2"...> Now, in JQuery, I am attempting to filter between the div elements based on the value of the c ...

Tips for Setting Up Next.js 13 Route Handlers to Incorporate a Streaming API Endpoint via LangChain

I am currently working on establishing an API endpoint using the latest Route Handler feature in Nextjs 13. This particular API utilizes LangChain and streams the response directly to the frontend. When interacting with the OpenAI wrapper class, I make sur ...

Exploring the possibilities of utilizing classes in testing scenarios with Vue, Cypress, and Cucumber

I am currently working on setting up e2e tests using Cypress and Cucumber for my project. The application is built with Vue CLI 4.1.1, and I have added the package cypress-cucumber-preprocessor (V1.19.0) via NPM. Update: After extensive research and tes ...

How to make a straightforward task list using ExpressJS

As a beginner, I am attempting to create a basic todo list using ExpressJS. Currently, my goal is to simply display some hardcoded todos that I have in my application. However, I seem to be struggling to identify the mistake in my code. Any assistance woul ...

My goal is to display the products on the dashboard that have a quantity lower than 10. This information is linked to Firestore. What steps can I take to enhance this functionality?

{details.map((val, colorMap, prodName) => { I find myself a bit perplexed by the conditional statement in this section if( colorMap < 10 ){ return ( <ul> <li key= ...

Receiving a 500 status code upon converting a SqlDataReader into Json format

Getting a status 500 error and not sure where I am going wrong. When I click on the 'Getcustomers' button, the 'GetCustomers' method is called which returns JSON. Script: <script> var MyApp = angular.module("MyApp", []); ...

Comparing JSON objects with JavaScript models: A guide

Currently I'm working with angular 2 and I have an array of data. data: MyModel[] = [ { id: 1, name: 'Name', secondName: 'SecondName' } In addition, I have created the interface MyModel: interface MyModel { id: number, nam ...

Tips for hiding a sidebar by clicking away from it in JavaScript

My angular application for small devices has a working sidebar toggling feature, but I want the sidebar to close or hide when clicking anywhere on the page (i.e body). .component.html <nav class="sidebar sidebar-offcanvas active" id="sid ...

Having difficulty retrieving the selected value in JSPDF

I am attempting to convert my HTML page into a PDF format by utilizing the following code: domtoimage.toPng(document.getElementById('PrintForm')) .then(function (blob) { var pdf = new jsPDF('p', &apo ...

Adjust the color of input labels using jQuery validate

I have a form where I want to change the class of the input labels when a specific field fails validation. My goal is to add the 'error' class to the spans that are directly above any invalid form elements. Here is an example of my HTML structur ...

The jQuery Ajax Error is consistently being triggered

I'm puzzled as to why my custom callback error function keeps getting triggered. When I remove this callback function, the success callback works just fine. Some sources online suggest that it could be an encoding issue, but I don't think that&a ...

Implementing a function as the `data-*` attribute for an element in Angular 6

I have a question about my component.ts file: import { Component, OnInit, AfterViewInit, ElementRef, Inject } from '@angular/core'; import { DOCUMENT } from '@angular/platform-browser'; import { environment } from '../../../enviro ...

safely sending different form inputs in a Ruby on Rails form

Within this snippet, you'll find a part of a table with a form. Each row has its own submit button, which means users have to click on each one individually. I'm currently working on changing this so there is just one button for submission. < ...