简体   繁体   English

我应该如何将 cookie 与 Svelte 和 Sapper 一起使用?

[英]How should I use cookies with Svelte and Sapper?

I'm using Svelte and Sapper for a project.我在一个项目中使用 Svelte 和 Sapper。 Let's say I have some code that needs to read a cookie before it runs, and that code is in a route at say /profile or something.假设我有一些代码需要在运行之前读取 cookie,并且该代码位于/profile或其他位置的路由中。

My understanding is that Sapper provides no guarantees where the code will run.我的理解是 Sapper 不保证代码将在何处运行。 If I put the code in regular <script> tags or maybe an onMount block, when a user requests /profile directly from the server, the code still execute on the server (and fail) but then execute again on the client:如果我将代码放在常规<script>标记或onMount块中,当用户直接从服务器请求/profile ,代码仍会在服务器上执行(并失败),但会在客户端上再次执行:

<script>
import { getCookie } from "../../myUtilities.js";

const myCookieValue = getCookie("myCookie");

async function myRuntimeAction() {
   let res = fetch(`https://www.example.com/api/${myCookieValue}`);
   ...
}
</script>

<form on:submit|preventDefault={myRuntimeAction}>
    <button>
      Take Action!
    </button>
</form>

Is there an idiomatic Svelte / Sapper way to guarantee code only runs client-side, when it has access to cookies?是否有一种惯用的 Svelte / Sapper 方式来保证代码在可以访问 cookie 时仅在客户端运行?

I found two ways to solve this:我找到了两种方法来解决这个问题:

1. Access cookies inside of functions that will only be executed client-side at runtime 1. 访问仅在客户端运行时执行的函数内部的 cookie

The root of the problem is that my variable declaration was a top-level declaration.问题的根源在于我的变量声明是顶级声明。 Simply moving the code that accesses the cookie inside of a function that is called only at runtime fixes the issue:只需将访问 cookie 的代码移动到仅在运行时调用的函数中即可解决此问题:

async function myRuntimeAction() {
   const myCookieValue = getCookie("myCookie");
   let res = fetch(`https://www.example.com/api/${myCookieValue}`);
   ...
}

2. Check process.browser before trying to access cookies 2. 在尝试访问 cookie 之前检查 process.browser

Svelte exposes process.browser to ensure code only executes in the browser: Svelte 公开process.browser以确保代码仅在浏览器中执行:

if (process.browser) {
    const myCookieValue = getCookie("myCookie");
}

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

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