【发布时间】:2022-01-29 09:04:00
【问题描述】:
我正在重新编写我的问题和代码示例,以便于理解。
当我调用这个 PUT 端点时,cookie 设置正确。
export const put: RequestHandler<Locals> = async (event) => {
const userInfo = {
refresh_token: Math.random().toString(),
};
const json = JSON.stringify(userInfo);
const jwt = cookie.serialize("jwt", json, {
httpOnly: true,
path: "/",
});
const headers = {
"Set-Cookie": [jwt],
};
return {
status: 200,
headers,
body: {},
};
};
当我调用这个 GET 端点时,cookie 没有设置。
export const get: RequestHandler<Locals> = async (event) => {
const userInfo = {
refresh_token: Math.random().toString(),
};
const json = JSON.stringify(userInfo);
const jwt = cookie.serialize("jwt", json, {
httpOnly: true,
path: "/",
});
const headers = {
"Set-Cookie": [jwt],
};
return {
status: 200,
headers,
body: {},
};
};
这是发送到 fetch 的选项,其中方法等于每种情况下的“GET”或“PUT”:
const opts: RequestInit = {
method,
credentials: "include",
headers: {
"Content-Type": "application/json",
},
};
if (data) {
opts.body = JSON.stringify(data);
}
【问题讨论】:
-
您可以尝试在
handle挂钩中设置cookie 吗? kit.svelte.dev/docs#hooks-handle—response.headers.append('set-cookie', jwt) -
但是我如何将 JWT 从端点发送回钩子句柄?像这样尝试但没有成功,PUT 有效,GET 无效。 const headers = { refresh_token: JSON.stringify(userInfo.refresh_token), "Set-Cookie": [jwt], };
-
我使用来自端点的 event.locals 发送了 JWT,它工作了。 Cookie 设置正确@kenset
-
测试了一切,一切正常。谢谢@kenset
-
很高兴听到这个消息!我会写下来给未来的读者。