Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/sockets/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 检查端点是否工作,如果不工作,请使用axios获取另一个URL_Javascript_Axios - Fatal编程技术网

Javascript 检查端点是否工作,如果不工作,请使用axios获取另一个URL

Javascript 检查端点是否工作,如果不工作,请使用axios获取另一个URL,javascript,axios,Javascript,Axios,我试图了解pokeapi和axios的API使用情况,他们似乎在某些端点上遇到了问题,有时返回404错误。我想用这个错误来练习 我有以下代码: const pokemonDataList = [] for(i = 1; i ≤ quantity) { const url = `https://pokeapi.co/api/v2/pokemon/${i}/` pokemonDataList.push(await axios.get(url)) } 当我运行它时,一切都会工作,直

我试图了解pokeapi和axios的API使用情况,他们似乎在某些端点上遇到了问题,有时返回404错误。我想用这个错误来练习

我有以下代码:

const pokemonDataList = []

for(i = 1; i ≤ quantity) {
    const url = `https://pokeapi.co/api/v2/pokemon/${i}/`
    pokemonDataList.push(await axios.get(url))
}
当我运行它时,一切都会工作,直到访问死端点,然后我的本地服务停止运行并返回未处理的错误消息

我想做的是当

等待axios.get(url)

获取一个错误,如404或500,我希望能够从另一个端点获取,然后返回初始循环,如下所示:

const pokemondalist=[]

for(i = 1; i ≤ quantity) {
    const url = `https://pokeapi.co/api/v2/pokemon/${i}/`
    if(axios.get(url) === success) {
        pokemonDataList.push(await axios.get(url))
    } else {
        pokemonDataList.push(await axios.get(anotherUrl))
    }
}

有没有这样的方法?

如果在axios调用期间发生错误,您可以使用try/catch来处理发生的错误:

for(i = 1; i ≤ quantity) {
    const url = `https://pokeapi.co/api/v2/pokemon/${i}/`
    try{
        pokemonDataList.push(await axios.get(url))
    } 
    catch (error) {
        console.log(`Error occured on main endpoint ${url}: ${error.message}`);
        console.log(`Fetching data form: ${anotherUrl}`);
        pokemonDataList.push(await axios.get(anotherUrl));
    }
}

如果在axios调用期间发生错误,您可以使用try/catch来处理发生的错误:

for(i = 1; i ≤ quantity) {
    const url = `https://pokeapi.co/api/v2/pokemon/${i}/`
    try{
        pokemonDataList.push(await axios.get(url))
    } 
    catch (error) {
        console.log(`Error occured on main endpoint ${url}: ${error.message}`);
        console.log(`Fetching data form: ${anotherUrl}`);
        pokemonDataList.push(await axios.get(anotherUrl));
    }
}

使用承诺来处理错误,如下所示:

await axios.get(url).then((response) => {
   console.log(response);

   // Do something on success
}).catch((error) => {
   console.error(error);

   // Do something on error...
});

使用承诺来处理错误,如下所示:

await axios.get(url).then((response) => {
   console.log(response);

   // Do something on success
}).catch((error) => {
   console.error(error);

   // Do something on error...
});