Notice: 函数 WP_Scripts::localize 的调用方法不正确$l10n 参数必须是一个数组。若要将任意数据传递给脚本,请改用 wp_add_inline_script() 函数。 请查阅调试 WordPress来获取更多信息。 (这个消息是在 5.7.0 版本添加的。) in /data/www/appblog/wp-includes/functions.php on line 6131

Vue使用axios实现登录验证拦截及页面跳转

定义路由时添加一个自定义字段requireAuth

path: '/repository',
name: 'repository',
meta: {
  requireAuth: true,  // 添加该字段,表示进入这个路由是需要登录的
},
component: Repository

路由跳转前权限验证

router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {  // 判断该路由是否需要登录权限
    if (store.state.token) {  // 通过vuex state获取当前的token是否存在
      next();
    } else {
      next({
        path: '/login',
        query: {redirect: to.fullPath}  // 将跳转的路由path作为参数,登录成功后跳转到该路由
      })
    }
  } else {
    next();
  }
}

这种方式只是简单的前端路由控制登录拦截,并不能真正阻止用户访问需要登录权限的路由。

还有一种情况便是:当前token失效,但是token依然保存在本地。此时访问需要登录权限的路由时,实际上应该让用户重新登录。

最终需要结合 HTTP拦截器 + 后端接口返回的HTTP状态码 判断。

请求与响应拦截器

统一处理所有HTTP请求和响应,使用axios的拦截器。每次路由跳转,都先让后台验证一下token是否有效,在http头添加token,当后端接口返回 403 Unauthorized(未授权) ,让用户重新登录。

// http request 拦截器
axios.interceptors.request.use(
  config => {
    if (store.state.token) {  // 判断是否存在token,如果存在,则每个http header都加上token
      config.headers.Authorization = `token ${store.state.token}`;
    }
    return config;
  },
  err => {
    return Promise.reject(err);
  });
// http response 拦截器
axios.interceptors.response.use(
  response => {
    return response;
  },
  error => {
    if (error.response) {
      switch (error.response.status) {
        case 403:
          // 返回 403 清除token信息并跳转到登录页面
          store.commit(types.LOGOUT);
          router.replace({
            path: 'login',
            query: {redirect: router.currentRoute.fullPath}
          })
          break
        defualt:
          break
      }
    }
    return Promise.reject(error.response.data)  // 返回接口返回的错误信息
  });

登出功能也就很简单,只需要把当前token清除,再跳转到首页即可。

上一篇 Vue更好的HTTP框架axios.js
下一篇 Vue.js插件总结