当我从 nuxtjs 发送登录请求时,我在后端使用 laravel/passport 进行身份验证,并使用 nuxtjs 作为前端,如果登录成功,我将返回令牌和用户信息作为响应,然后用户将被重定向到/profile页面,但是/profile当我返回时在页面 中this.$auth.loggedIn我得到了false!
登录.vue
<script>
export default {
data() {
return {
auth: false,
email: "",
password:""
}
},
methods: {
async login() {
try {
const data = { email: this.email, password: this.password }
await this.$auth.loginWith('local', { data:data})
.then(() => this.$router.push('/profile'))
} catch (e) {
}
}
}
}
</script>
Run Code Online (Sandbox Code Playgroud)
配置文件.vue
<template>
<div class="mt-6">loggedInUser: {{ loggedInUser }}</div>
</template>
<script>
export default{
data() {
return {
loggedInUser:this.$auth.loggedIn
}
}
}
Run Code Online (Sandbox Code Playgroud)
nuxt.config.js
auth: {
strategies: {
provider: 'laravel/passport',
local: {
user: {
property: false,
autoFetch: true
},
endpoints: {
login: { url: '/login', method: 'post', propertyName: 'token' },
user: { url: '/user', method: 'get' }
},
clientId: 'cleint_id',
clientSecret: 'client_secret'
}
}
},
modules: [
'@nuxtjs/axios',
// https://go.nuxtjs.dev/bootstrap
'bootstrap-vue/nuxt',
'@nuxtjs/auth',
],
axios: {
baseURL: "http://prostudent.test/api"
},
Run Code Online (Sandbox Code Playgroud)
由于登录发生在后端,nuxt 如何知道用户已登录?
这是在我点击登录后,我被重定向到个人资料,并且登录的响应符合预期,消息,令牌和信息,但在/profile页面中似乎我没有登录!
即使您没有将 Vuex 与您自己的模块一起使用,nuxt/auth它也会为您创建一些状态。因此存在this.$store.state.auth.loggedIn. 顺便说一句,您是否尝试附加$store到您的文件中profile.vue?如文档所示。
像这样
<template>
<div class="mt-6">
loggedInUser: {{ $store.state.auth.loggedIn }}
</div>
</template>
Run Code Online (Sandbox Code Playgroud)
另外,打开你的 vue devtools 并检查 vuex 选项卡,你会在那里发现一些不错的状态。
这也回答了你的另一个问题
由于登录发生在后端,nuxt 如何知道用户已登录?
Nuxt 检查来自服务器的响应,并根据响应将 的状态设置auth.loggedIn为true或false。
这些是成功登录所需执行的 2 个步骤(使用 loginWith + setUser)。
const succesfulLogin = await this.$auth.loginWith('local', {
data: {
email: this.email,
password: this.password,
},
})
if (succesfulLogin) {
await this.$auth.setUser({
email: this.email,
password: this.password,
})
}
Run Code Online (Sandbox Code Playgroud)
之后,loggedIn可能会传递到true.
当然,user也可以从后端获取信息。取决于您的用例。
| 归档时间: |
|
| 查看次数: |
6113 次 |
| 最近记录: |