在与 Sapper 和 Svelte 的会话中写作

Sou*_*euh 6 session svelte sapper

我按照RealWorld 示例编写了一个带有会话管理的 Sapper 应用程序:

polka()
  .use(bodyParser.json())
  .use(session({
    name: 'kidways-app',
    secret: 'conduit',
    resave: false,
    saveUninitialized: true,
    cookie: {
      maxAge: 31536000
    },
    store: new FileStore({
      path: 'data/sessions',
    })
  }))
  .use(
    compression({ threshold: 0 }),
    sirv('static', { dev }),
    pdfMiddleware,
    sapper.middleware({
      session: req => ({
        token: req.session && req.session.token
      })
    })
  )
  .listen(PORT, err => {
    if (err) console.log('error', err);
  });
Run Code Online (Sandbox Code Playgroud)

然后在我的_layout.sevlte

<script context="module">
  export async function preload({ query }, session) {
    console.log('preload', session)
    return {
      // ...
    };
  }
</script>

<script>
  import { onMount, createEventDispatcher } from 'svelte';
  import { Splash } from 'project-components';
  import * as sapper from '@sapper/app';
  import { user } from '../stores';
  import client from '../feathers';

  const { session } = sapper.stores();

  onMount(async () => {
    try {
      await client.reAuthenticate();
      const auth = await client.get('authentication');
      user.set(auth.user);
      $session.token = 'test';
    } catch (e) {
    } finally {
      loaded = true;
    }
  });

  console.log($session)
</script>

<h1>{$session.token}</h1>
Run Code Online (Sandbox Code Playgroud)

这适用于客户端渲染,但令牌在预加载时仍未定义,这使我的 SSR 模板渲染损坏。

我错过了什么?

Ric*_*ris 12

当页面呈现时,session根据您在此处指定的函数的返回值进行填充:

sapper.middleware({
  session: req => ({
    token: req.session && req.session.token
  })
})
Run Code Online (Sandbox Code Playgroud)

因此,虽然客户端可能拥有最新的令牌,但它不会在页面重新加载时生效,除非您以某种方式将令牌以会话中间件知道的方式持久保存到服务器。

通常你会通过拥有一个服务器路由来实现这一点,比如routes/auth/token.js什么......

export function post(req, res) {
  req.session.token = req.body.token;

  res.writeHead(200, {
    'Content-Type': 'application/json'
  });

  res.end();
}
Run Code Online (Sandbox Code Playgroud)

...并从客户端发布令牌:

onMount(async () => {
  try {
    await client.reAuthenticate();
    const auth = await client.get('authentication');
    user.set(auth.user);

    await fetch(`auth/token`, {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ token })
    });

    // writing to the session store on the client means
    // it's immediately available to the rest of the app,
    // without needing to reload the page
    $session.token = 'test';
  } catch (e) {
  } finally {
    loaded = true;
  }
});
Run Code Online (Sandbox Code Playgroud)