【问题标题】:How to pass props to a SvelteKit endpoint如何将道具传递给 SvelteKit 端点
【发布时间】:2021-09-29 04:04:08
【问题描述】:

我正在尝试将道具传递给 SvelteKit 端点异步函数,但没有成功。我正在使用商店来传递 value,但由于我不明白的原因,当我尝试在函数中获取它时 value 是未定义的。

谁能看到我做错了什么,要么访问存储值,要么是否有更好的方法将 value 传递给函数?谢谢!埃里克

index.svelte

<script lang="ts">
  
  import { sampleData } from "~/data/sample";

  async function handleClick() {
    $sampleData = {value: "Fancy"};
    const result = await (await fetch(`/apis/ping`)).json();
    console.log("result", result);
  }
</script>


<button on:click={handleClick}>Ping</button>
ping.ts

import { sampleData } from "~/data/sample";
import { get as getDoc } from "svelte/store";


export async function get(): Promise<{ body: any }> {

  const _sampleData = getDoc(sampleData);
  const value = _sampleData.value;
  console.log("value", value);  

  // const value = "Fancy";

  const result = await (
    await fetch(`https://my-server/app/ping?value=${value}`)
  ).json();

  console.log("result", result);

  return {
    body: result,
  };
}

【问题讨论】:

    标签: endpoint sveltekit


    【解决方案1】:

    存储在服务器和客户端之间不共享,因此端点中的存储仍将是它的初始值(在您的情况下为 undefined

    您必须将前端(在浏览器上执行的内容)和后端或端点(在服务器上执行)视为完全独立的东西。

    也就是说,您应该将参数与 fetch 一起传递,无论是在正文中还是作为查询参数。

    在体内

    // in the client
    fetch('/apis/ping', {
      body: JSON.stringify({ value: "Fancy" }),
      headers: {
        'Content-Type': 'application/json'
      }
    })
    
    // in the endpoint
    export async function get({ body }) {
      const sampleData = body;
    }
    

    作为查询参数

    // in the client
    fetch('/apis/ping/?value=Fancy')
    
    // in the endpoint
    export async function get({ query }) {
      const sampleData = query.get('value')
    }
    

    【讨论】:

    • 谢谢!这让我几乎一路走来......不知道为什么,但我不得不将所有东西都包装在额外的等待中......下面的完整解决方案
    【解决方案2】:

    以下是最终为我工作的:

    index.svelte

    <script lang="ts">
      const value = "Fancy";
      async function handleClick() {
        let response = await(await fetch(`/apis/ping/?value=${value}`)).json();
        console.log("response", response);
      }
    </script>
    
    
    <button on:click={handleClick}>Ping</button>
    

    ping.ts

    export async function get({ query }) {
      const value = query.get("value");
      const result = await (await fetch(`https://my-server/app/ping?value=${value}`)).json();
    
      return {
        body: result,
      };
    }
    

    不知道为什么需要额外的等待和强制转换为 json

    【讨论】:

    • await fetch().then(res =&gt; res.json()) 不让双重等待
    猜你喜欢
    • 2021-09-13
    • 1970-01-01
    • 2019-01-07
    • 1970-01-01
    • 2020-05-05
    • 2020-12-22
    • 2017-10-03
    相关资源
    最近更新 更多