简体   繁体   English

Svelte:使用 fetch() 处理发布请求的 JSON 响应

[英]Svelte: process JSON response of a post request with fetch()

I have a question regarding svelte and an API.我有一个关于 svelte 和 API 的问题。

I want to make a request to an API and then return data[170] from my getCurrentData function.我想向 API 发出请求,然后从我的 getCurrentData 函数返回数据 [170]。 I want to display currentData[101] and currentData[102] in the svelte code.我想在苗条的代码中显示 currentData[101] 和 currentData[102]。 But this does not work and I get an error from svelte saying it failed to rerender.但这不起作用,我从 svelte 那里得到一个错误,说它无法重新呈现。 However, if I return data[170][101] from the function and then in the svelte code just write {currentData} (instead of currentData[101]) it works.但是,如果我从函数返回 data[170][101],然后在精巧的代码中只写 {currentData}(而不是 currentData[101]),它就可以工作。

data[170] looks like this: image1数据 [170] 看起来像这样: image1

currentDataPromise = getCurrentData(request1, request2);


async function getCurrentData(request1, request2) {        
        const response = await fetch(url, {
            method: "POST",
            
            body: JSON.stringify({
                "801": {
                    "170": null
                }
            }),
            
            headers: {
                "Content-Type": "application/json; charset=utf-8",
                //other headers
            }
        });
        const json = await response.json();
        const data = json[801];

        if (data) {
            console.log(data[170]); //see image1
            return data[170];
        } else {
            throw new Error("No data available...");
        }
    };
{#await currentDataPromise}
     <p>Loading...</p>
{:then currentData}
    <p class="value">{currentData[101]} and {currentData[102]}</p>
{:catch error}
    <p class="error">{error.message}</p>
{/await}

Since I don't want to make an unnecessarily high amount of requests I'd really like to figure out why the first option isn't working.因为我不想提出不必要的大量请求,所以我真的很想弄清楚为什么第一个选项不起作用。 Any idea why this is not working?知道为什么这不起作用吗?

Edit: using JSON format in body (but did not change anything)编辑:在正文中使用 JSON 格式(但没有改变任何东西)

There is probably something off with your data or how you read it.您的数据或您阅读数据的方式可能有问题。 The error could also be in the code that you did not include.错误也可能出现在您未包含的代码中。

The fact that you are using magic indices all over makes it highly likely that you end up reading the wrong value or end up a level off.事实上,您到处都在使用魔术指数,这很可能导致您最终读取错误的值或最终趋于平稳。 Try to use named properties instead of just arrays for everything.尝试对所有内容使用命名属性,而不仅仅是数组。

Here is an example that shows that the Svelte code works just fine if the data is there:这是一个示例,表明如果数据存在,Svelte 代码就可以正常工作:

<script>
    let currentDataPromise = getCurrentData();
    async function getCurrentData() {
        const url = 'data:application/json,' + encodeURIComponent(JSON.stringify({
            [801]: {
                [170]: {
                    [101]: 'Value 101',
                    [102]: 'Value 102',
                }
            }
        }));
        const response = await fetch(url);
        const json = await response.json();
        const data = json[801];

        if (data) {
            return data[170];
        } else {
            throw new Error("No data available...");
        }
    };
</script>

{#await currentDataPromise}
     <p>Loading...</p>
{:then currentData}
    <p class="value">{currentData[101]} and {currentData[102]}</p>
{:catch error}
    <p class="error">{error.message}</p>
{/await}

REPL REPL

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM