使用Sapper和Svelte编写会话

6

我按照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);
  });

然后,在我的_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>

这个工作是在客户端渲染上进行的,但是token在预加载时仍然未定义,导致我的服务器端渲染模板渲染出现问题。
我错过了什么?
1个回答

12
当页面渲染时,`session`根据您在此处指定的函数的返回值进行填充。
sapper.middleware({
  session: req => ({
    token: req.session && req.session.token
  })
})

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

通常,您可以通过设置服务器路由来实现此目的,例如routes/auth/token.js或类似的路由...

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

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

  res.end();
}

...并且从客户端提交令牌:

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;
  }
});

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接