Home > database >  How to refresh my page when encountering a 404 error in JavaScript
How to refresh my page when encountering a 404 error in JavaScript

Time:07-24

I'm using MovieDB API to create a website. I'm randomly getting movie id's and generating the genres this way. However, sometimes, an id which doesn't exist gets generated and it throws a 404 error. I want to write something like: if response == 404 then rerun my code or refresh the page. I tried writing this logic many ways but I can't seem to get it to work. Thank you in advance.

async function getAPI(api_url) {
    const response = await fetch(api_url)
    var data = await response.json()
    var g = data.genres

    let user_genre = document.getElementById("input").value
    for (let i = 0; i < g.length; i  ) {
        console.log(g[i].name)
    }

}

CodePudding user response:

You can check response.ok to check if the fetch succeeded, or response.status for the exact HTTP status.

const response = await fetch(api_url);
if (!response.ok) location.reload();

CodePudding user response:

you can repeat function

async function getAPI(api_url) {
    const response = await fetch(api_url)
    if(!response.ok) {
        return getAPI(api_url)
    }
    var data = await response.json()
    var g = data.genres

    let user_genre = document.getElementById("input").value
    for (let i = 0; i < g.length; i  ) {
        console.log(g[i].name)
    }
}
  • Related