1

Basically I have this really simple javascript that gets the ?user=example query string and if it is not found in the list it does nothing but if it is then it redirects to the according profile.

<script>
 var url = window.location.toString();
       var query_string = url.split("?");
               if (query_string[1] === 'user=example') {
       document.location = "https://streety.org/users/example";
               }
</script>
             

Since I have more than one user it would be counterintuitive to put a bunch of if statements for every use so I want to make it so instead it gets the data and puts it into the url https://streety.org/users/ and then tests if the server returns 404 or 200, if 404 then do nothing if 200 then redirect user to that page

How could I do test for a valid page?

Sharkii
  • 19
  • 1

1 Answers1

-1

This should get you close to what you want.

// Get the URL
const urlQuery = window.location.search;
// use URLSearchParams JS Class to get the query parameters
const urlParams = new URLSearchParams(urlQuery);
// If urlParams contains the "user" parameter
if (urlParams.has('user')) {
  // get the value for the user parameter
  let user = urlParams.get('user');
  // Fetch the URL
  fetch('https://streety.org/users/' + user)
    // check the promise
    .then(response => {
    // if the response is OK (between 200-299 response code)
    if (response.ok) {
      // redirect
      document.location = 'https://streety.org/users/' + user;
    }
  });
}
disinfor
  • 10,865
  • 2
  • 33
  • 44
  • 1
    `is_valid` will always be `false` at that `if` statement because fetch is async/returns a promise – Samathingamajig Jul 23 '21 at 21:07
  • 1
    I just realized you are correct! I'm working on a fix for the answer. – disinfor Jul 23 '21 at 21:08
  • Thanks to @Samathingamajig I updated the answer (based on my basic knowledge of promises) removing the test variable since we can use a promise for that. – disinfor Jul 23 '21 at 21:23
  • @Sharkii awesome! Can you please upvote it and mark it as accepted? The down vote will make people think that it doesn't answer the question. – disinfor Jul 25 '21 at 00:13