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)
}
}
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();
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)
}
}
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.