如何将数据从端点传递到 SvelteKit 中的 getSession()?

我正在尝试将一个对象从端点传递给 getSession ,我相信它们都在服务器中运行。我可以得到用 cookie 传递的值,但不能得到用 request.locals.<variable> 传递的值:

src/hooks.ts

import cookie from 'cookie'

export async function handle({request, resolve}) {
  const cookies = cookie.parse(request.headers.cookie || '')

  request.locals.accessToken = cookies.accessToken
  request.locals.refreshToken = cookies.refreshToken

  const response = await resolve(request)

  const accessToken = `accessToken=${request.locals.accessToken || ''}; Path=/; Secure; HttpOnly;`
  const refreshToken = `refreshToken=${request.locals.refreshToken || ''}; Path=/; Secure; HttpOnly;`

  response.headers['set-cookie'] = [accessToken, refreshToken]

  return response
}

export async function getSession(request) {
    console.log('check request local', request.locals)
  return {
    accessToken: request.locals.accessToken,
    refreshToken: request.locals.refreshToken,
    user: request.locals.user
  }
}

我的端点:

export const post: RequestHandler<Locals, FormData> = async(req) => {
    const name = req.body.get("name")
    const password = req.body.get("password")

    if (!name || !password) {
        return {
            status: 400,
            body: {
                message: "Missing username or password"
            }
        }
    }
    const { access_token, refresh_token } = await getAccessToken(name, password)

  req.locals.accessToken = access_token
  req.locals.refreshToken = refresh_token

    const user = await getUser(access_token)

    req.locals.user = user

  return {
    status: 302,
    headers: {
      location: '/lobby'
    }
  }
}

如果我想将带有 getUser 的数据传递给 handle ,我应该在 request.locals 中运行 getSession 吗?

编辑

我实际上能够在 request.locals.user 之后获得 const response = await resolve(request) 的值,但不能在 resolve 之前获得。这是为什么?

stack overflow How to pass data from endpoint to getSession() in SvelteKit?
原文答案

答案:

作者头像

我将数据从端点传递到 getSession ,并在 handle 函数中设置一个cookie,如前所述:

//  src/hooks.js

import cookie from 'cookie';

export const handle = async ({ event, resolve }) => {
    const cookies = cookie.parse(event.request.headers.get('cookie') || '');
    event.locals.user = cookies.user || null;
    const response = await resolve(event);
    if (event.locals.user) {
        response.headers.set(
            'set-cookie',
            cookie.serialize('user', event.locals.user, {
                path: '/',
                httpOnly: true
            })
        );
    }
    return response;
};

export async function getSession(event) {
    return {
        user: event.locals.user
    }
}
作者头像

在你的 hooks.ts 的 handle() 中获取用户信息(在 const response = await resolve(request) 之前是一个好地方。这是因为如果你要根据用户是谁来限制对页面或端点的访问(或者可能是用户角色),您希望在调用页面或端点之前发生这种情况。

关于您在解决请求之前为什么不填充 request.locals.user 的其他问题,这对我来说似乎是一个错误。我可以确认同样的行为。您可能希望将其作为问题提交。