-1

I have a .js file from which I am assigning several URL addresses that are then being accessed in the frontend, i.e.

let serviceURL1 = "http:/....com"

let serviceURL2 = "http:/....com"

This script is loaded in to the HTML frontend and serviceURL1 is accessed on button click.

How can I check if each of these is reachable, and if not, assign an alternative URL?

The approach I'm trying is like this:

const https = require('https')
https.get('http://serviceURL1.uk/', res => {
    if(res.statusCode === 200) {
        console.log('Service online.')
        service1URL= "http://serviceURL1.uk/";
    } else {
        console.log('Service offline. Redirecting to backup URL.')
        service1URL= "http://serviceURLbackup.uk/";
    }
})

But it doesn't seem to be working and I don't really know what I'm doing to be honest, I appreciate any help from anyone.

Aegard
  • 45
  • 4
  • Does this answer your question? [Check if a JavaScript string is a URL](https://stackoverflow.com/questions/5717093/check-if-a-javascript-string-is-a-url) – human bean Dec 01 '22 at 15:06
  • @humanbean Your suggested duplicate does not answer the question. The OP here is not asking if a particular string value represents a valid URL syntactically, but rather if that URL is reachable over the network. – esqew Dec 01 '22 at 15:47
  • "*it doesn't seem to be working*" Can you elaborate? What errors are you seeing? The presence of this line `const https = require('https')` seems to indicate you're attempting to use a Node.js-specific construct, which would not work in-browser. Where did you get this code from, and how did you reach the conclusion that it should work in a browser-based JavaScript runtime? – esqew Dec 01 '22 at 15:49

1 Answers1

1

Try this:

const https = require('https')
https.get('http://serviceURL1.uk/', res => {
    if(res.statusCode === 200) {
        console.log('Service online.')
        service1URL= "http://serviceURL1.uk/";
    } else {
        console.log('Service offline. Redirecting to backup URL.')
        service1URL= "http://serviceURLbackup.uk/";
    }
}).on('error', (e) => {
  console.log('Service offline. Redirecting to backup URL.')
        service1URL= "http://serviceURLbackup.uk/";
});

Unreachable service will throw error. Your code was checking result from reachable server, so it won't work it request cannot be fulfiled.