簡體   English   中英

Axios Ajax,從調用 API 返回未定義

[英]Axios Ajax, returning undefined from call to API

我遇到了一個問題,當我嘗試進一步深入數據時,我的 ajax 調用返回 undefined。

請參閱下面的 API 文檔。

https://www.thecocktaildb.com/api.php

所以我使用的是ID方法。

https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=11007

這是我進行調用的構造函數...

export default class Recipe {
    constructor(id) {
        this.id = id;
    }

    async getRecipe() {
        try {
            const res = await axios(`https://www.thecocktaildb.com/api/json/v1/1/lookup.php?i=` + this.id);
            this.title = res.data.drinks.strDrink;
            this.image = res.data.drinks.strDrinkThumb;
            this.measure = res.data.drinks.strMeasure1;
            this.ingredients = res.data.drinks.strIngredient1;
            this.method = res.data.drinks.strInstructions;
        } catch (error) {
            alert(error);
        }
    }
}

這是我測試輸出的地方...

const r = new Recipe(11007);
r.getRecipe();
console.log(r);

我想知道我是否在使用他們的測試 API 時超出了 API 調用限制。 但是我仍然可以在其他地方成功撥打電話。

奇怪的是,例如,如果我對 API 進行了相同的調用,但只有 res.data.drinks,它將返回傳遞給函數的 ID 雞尾酒的完整詳細信息。

但是當我嘗試進一步深入時,它只會返回未定義。

提前致謝。

當您聲明一個async函數時,您需要await異步調用的返回。 或者,您也可以使用標准的 Promise API

someAsyncFunction().then(result => console.log(result))
                   .catch(err => console.log(err));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM