【发布时间】:2023-03-26 13:21:02
【问题描述】:
用例:Vue3 应用程序使用 express 作为 API 后端。 Express 使用 express-sessions 建立服务器端会话,该会话发送到浏览器并在每个后续请求中接收。
如果会话 cookie 不存在,我正在尝试创建路由保护以防止访问某些路由。
"vue": "^3.0.11",
"vue3-cookies": "1.0.1",
我已经安装了以下 NPM 包
https://www.npmjs.com/package/vue3-cookies
然后在main.js
import VueCookies from 'vue3-cookies'
app.use(VueCookies);
然后在router/index.js
function requireAuth(to,from,next){
console.log(this);
console.log(this.$cookies.get('_ga'))
next();
}
const routes = [
{
path: '/',
name: 'ProtectedRoute',
component: ProtectedRoute,
beforeEnter:requireAuth
}
const router = createRouter({
history: createWebHistory(process.env.BASE_URL),
routes
})
Error: [Vue Router warn]: Unexpected error when starting the router: TypeError: Cannot read property '$cookies' of undefined
我试过了
this.$cookies.get('_ga')
Vue.$cookies.get('_ga')
window.$cookies.get('_ga')
没有工作。
我也尝试过将 Vue 导入 index.js 文件,但失败了,可能是因为在 Vue3 中你无法将 Vue 导入到组件中Vue.js 3: Cannot import Vue global object
问题好像是this,Vue和window都是undefined。我也试过这里的解决方案`this` undefined in vue-router beforeEach
router.beforeEach((to,from,next) => {
console.log(router.app); //still undefined!
});
救命!
【问题讨论】:
-
您到底想达到什么目的?为什么要尝试在 beforeEach 中获取 cookie?
-
也可能是包的问题,你试过用
document.cookie吗?看看它是否输出了什么? -
你的上下文有误,我想你可以试试 Vue.$cookies (先导入 Vue)
标签: javascript vue.js session-cookies vuejs3