简体   繁体   中英

JS redirect user based on a remote files existence

I'm trying to redirect a user based on the existence of a remote file. I'm not sure if this is even possible.

The code in website.com:

var result = doesFileExist("http://remote-website.com/verifier.php");
 if (result == true) {
    header("Location: https://website.com/"); 
} else {
    header("Location: https://website.com/error.php"); 
}

I see this error on the console:

Uncaught ReferenceError: doesFileExist is not defined

One possible way would be to send a GET request to the page, and check if the response code is 404 (not found):

fetch(url)
.then(function(response) {
  var status = response.status; //the response code, e.g. 200, 404, ...
  if(status == 404) {
    //do something
  }
});

Note that some websites automatically redirect you to a default error page if the requested file does not exist, and in that case the response code you get may not be a 404.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM