我正在为项目使用Svelte和Sapper。假设我有一些代码需要在运行前读取Cookie,并且该代码位于<script>
之类的路径中。
我的理解是,Sapper无法保证代码将在何处运行。如果我将代码放入常规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>
时,代码仍在服务器上执行(并失败),但是在客户端上再次执行:
// This will get called
NSLog("Did Set" + globalBool.description)
}
是否有一种惯用的Svelte / Sapper方法来确保代码只能在客户端访问cookie时运行?
答案 0 :(得分:0)
我发现了两种解决方法:
问题的根源是我的变量声明是一个顶级声明。只需将访问cookie的代码移到仅在运行时才调用的函数中即可解决此问题:
async function myRuntimeAction() {
const myCookieValue = getCookie("myCookie");
let res = fetch(`https://www.example.com/api/${myCookieValue}`);
...
}
Svelte公开process.browser
以确保代码仅在浏览器中执行:
if (process.browser) {
const myCookieValue = getCookie("myCookie");
}