异步 Axios 调用未在 Svelte 中执行:尝试使用结果会引发 TypeError: Cannot conversion undefined or null to object ;获取 API 工作

Jar*_*ler 9 axios svelte svelte-3

概括

  • 语境

  • 实际行为(问题)

  • 预期行为

  • 最小的、可测试的、可执行的示例

    • 数据

    • 来源

  • 笔记

  • 线索


语境

我正在尝试在 Svelt Web 应用程序中使用 Axios 从 URL 获取 JSON 对象列表http://localhost:1337/restaurants。此调用将在 Svelte 组件初始化时执行,类似于 Svelte 教程: https: //svelte.dev/tutorial/await-blocks

实际行为(问题)

当我打开包含 Svelte 组件的网页时,我在 Chromium 开发工具网络面板中看不到网络调用。

我可以在网页中看到此错误(显然要感谢我的{:catch}):

类型错误:无法将未定义或 null 转换为对象

预期行为

当我打开包含 Svelte 组件的网页时,我应该在 Chromium 开发工具网络面板中看到网络调用,并且它应该在列表项中显示每个 JSON 对象。

当然,绝对不能出现以下错误:

类型错误:无法将未定义或 null 转换为对象

最小的、可测试的、可执行的示例

数据

此示例使用 (Strapi) URL http://localhost:1337/restaurants,它返回以下 JSON 对象数组:

[{"id":1,"name":"Biscotte Restaurant","description":"欢迎光临 Biscotte 餐厅! Biscotte 餐厅提供采用新鲜优质产品烹制的美食,这些产品通常是本地产品,尽可能是有机产品,并且始终由充满激情的制作人。","published_at":"2021-10-02T20:04:26.780Z","created_at":"2021-10-02T19:40:30.378Z","updated_at":"2021-10-02T20: 04:26.816Z","类别":[{"id":2,"name":"早午餐","published_at":"2021-10-02T20:04:03.395Z","created_at":"2021- 10-02T19:41:15.186Z","updated_at":"2021-10-02T20:04:03.437Z"}]}]

来源

<script>
    import axios from 'axios';

    async function getRestaurants() {
            return await axios.get('http://localhost:1337/restaurants');
    }

    let restaurants_promise = getRestaurants();
</script>

<main>
    {#await restaurants_promise}
        <p>wait...</p>
    {:then restaurants}
        <p>The restaurants are:</p>
        {#each restaurants.data as restaurant}
            <li>
                {restaurant.name}
            </li>
        {/each}
    {:catch error}
        <p style="color: red">{error}</p>
    {/await}
</main>
Run Code Online (Sandbox Code Playgroud)

笔记

我不想使用 Strapi 的教程onMountthen/catch块,因为我更喜欢遵循 ​​Svelte 的教程(请参阅 Strapi 的教程:Strapi 教程)(“Strapi”因为实际上http://localhost:1337/restaurants是 Strapi URL)。我真的尝试坚持使用https://svelte.dev/tutorial/await-blocks

线索

  • 使用 Postman,我实际上可以获得 JSON 对象的 URL 列表,以便网络调用正常工作。所以有问题的显然是我的 Svelte 代码。

  • 使用 Fetch API 而不是 Axios,我的代码可以正常工作。我不再看到错误“TypeError:无法将未定义或 null 转换为对象”。

Ste*_*aes 8

将用户的配置与 axios 的 defaultConfig 合并的代码中似乎存在错误(不知何故 defaultConfig 是undefined)。

此问题是在 v0.21.2 中引入的,因此暂时降级到最新的 v0.21.1 应该可以。

  • 该问题在 0.24.0 版本上仍然存在 (3认同)

JHe*_*eth -1

看来你只需要等待实际数据。现在您正在等待呼叫,然后尝试迭代数据。

<script>
    import axios from 'axios';

    async function getRestaurants() {
            const res = await axios.get('http://localhost:1337/restaurants');
            const data = await res.data
            return data 
    }

    let restaurants_promise = getRestaurants();
</script>

<main>
    {#await restaurants_promise}
        <p>wait...</p>
    {:then restaurants}
        <p>The restaurants are:</p>
        {#each restaurants as restaurant}
            <li>
                {restaurant.name}
            </li>
        {/each}
    {:catch error}
        <p style="color: red">{error}</p>
    {/await}
</main>
Run Code Online (Sandbox Code Playgroud)