使用Axios和Async/Await解析嵌套的JSON [英] Parse Nested JSON Using Axios and Async/Await

查看:621
本文介绍了使用Axios和Async/Await解析嵌套的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从api获取数据,该api应该返回带有食谱数组的json对象.我在前端和Axios上使用React挂钩来执行请求.钩子运行了,但是尝试从响应中访问json数组时出现错误.

I am trying to fetch data from an api which should return a json object with an array of recipes. I am using React hooks on the front end and Axios to perform the request. The hook runs but I get an error while trying to access the json array from the response.

以下是示例api响应:

Here's the sample api response:

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

和我的代码以获取配方响应:

and my code to get the recipe response:

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调用有问题吗?

I have removed the hooks declarations and api url is https://api.myjson.com/bins/t7szj. The problem lies in getting the array from the response. Is there something wrong with my api call?

这是错误消息:

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}`)
    }
};

使用axios时,您不必在响应上调用res.json()(与fetch不同),因为axios会自动为您处理.这意味着axios默认将响应解析为JSON.

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.

与Axios同步/等待

这篇关于使用Axios和Async/Await解析嵌套的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆