使用 Axios 和 Async/Await 解析嵌套 JSON

Parse Nested JSON Using Axios and Async/Await

我正在尝试从一个 api 中获取数据,它应该 return 一个带有一系列食谱的 json 对象。我在前端使用 React hooks 和 Axios 来执行请求。挂钩运行但在尝试从响应访问 json 数组时出现错误。

这是示例 api 响应:

{
    count: 30,
    recipes: [objects, ... 29]
}

以及我获取食谱响应的代码:

const fetchRecipes = async () => {
    try {
        const recipeData = await Axios.get(api);
        console.log(recipeData);
        const recipes = await recipeData.json(); // error occurs here
        setRecipes(recipes);
        setLoading(false);
    } catch (err) {
        console.log(`Error occurred fetching recipes ${err}`)
    }
};

useEffect(() => {
    fetchRecipes();
}, []);

我删除了钩子声明,api url 是 https://api.myjson.com/bins/t7szj。问题在于从响应中获取数组。我的 api 通话有问题吗?

这是错误信息:

Error occurred fetching recipes TypeError: recipeData.json is not a function

你试过吗?

const fetchRecipes = async () => {
    try {
        const recipeData = await Axios.get(api);
        console.log(recipeData.data);
        const recipes = recipeData.data;
        setRecipes(recipes);
        setLoading(false);
    } catch (err) {
        console.log(`Error occurred fetching recipes ${err}`)
    }
};

you don't have to call res.json() on the response when using axios (unlike fetch) because axios handles that for you automatically. Meaning that axios parses the response to JSON by default.