路线更改的 Sapper 事件

Sapper event for route change

如果用户未通过身份验证,我需要将他们重定向到登录页面。我在 Vue.js 中需要类似 route.beforeEach 的东西,理想情况下:

sapper.beforeRouteChange((to, from, next) => {

  const isAuth = "[some session or token check]";

  if (!isAuth) {
    next('/login')
  }

  next()
})

我找到了 Sapper - protected routes (route guard) 这个问题,但我认为它不足以满足我的需求。如果 token 或 auth 在运行时发生变化怎么办?或者它是否包含在反应性中?

编辑 1: 我认为 Sapper GitHub 上的 this 问题解决了我的问题。

所以我把这段代码放到 /src/routes/_layout.svelte:

  import AuthMiddleware from "../methods/authMiddleware.js";
  import { goto, stores } from '@sapper/app';
  const { page } = stores();

  if (typeof window !== "undefined" && typeof document !== "undefined") {
    page.subscribe(({ path, params, query }) => {
      const from = window.location.pathname;
      const redirect = (href) => { goto(href); }

      AuthMiddleware.beforeChange(from, path, redirect, params, query);
    })
  }

这是 authMiddleware.js 文件:

export default class AuthMiddleware {

  static beforeChange(from, to, redirect, params, query) {

    if (!AuthMiddleware._isUserAuthenticated()) {
      redirect("/login");
    }
  }

  // ~

  static _isUserAuthenticated() {
    return true; // TODO: Implement
  }
}

可以在此处找到有关路由挂钩的更多信息

您也可以在 server.js 文件中使用 authenticationMiddleware.js

这是authenticationMiddleware.js文件

import { get, post } from "./../lib/api";
async function authenticationMiddleware(req, res, next) {
    let user = null
    const cookies = require('cookie-universal')(req, res);
    if (cookies.get('token')) {
        try {
            user = await get("users/me", null, cookies.get('token'));
        } catch (e) {
            console.log('err at users', e.toString());
        }
        req.user = user
        req.token = cookies.get('token')
    } else {
        req.user = {}
        req.token = null
        cookies.set('token', null)
    }
    next();
}
export { authenticationMiddleware }

例如https://github.com/itswadesh/sapper-ecommerce/blob/master/src/server.js