如何将 props 传递到 SvelteKit 端点

Jar*_*rks 4 endpoint sveltekit

我试图将 props 传递给 SvelteKit 端点异步函数,但没有成功。我正在使用 store 来传递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>
Run Code Online (Sandbox Code Playgroud)
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,
  };
}
Run Code Online (Sandbox Code Playgroud)

Ste*_*aes 5

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

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

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

在体内

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

作为查询参数

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