[英]Lose user data in Nuxt-auth fetchUser CustomStrategy
嗨,大家好! 我有自己的自定义策略来获取令牌,一切都很好,但是当刷新页面时,我丢失了用户数据并且 fetchUser 不起作用。 它不会将参数发送到 API 以再次获取用户数据。 接下来的工作流程是:1- 将参数发送到令牌 API 并获取令牌 2- 将参数发送到登录 API 以获取用户
//nuxt.config.js
customStrategy: {
_scheme: '~/schemes/customScheme',
endpoints: {
login: {
url: '/api/v1/token',
method: 'post',
propertyName: 'token',
headers: {'x-channel-id': 1}
},
user: {
url: '/api/v1/login',
method: 'post',
propertyName: false,
headers: {'x-channel-id': 1}
},
logout: null
}
}
customScheme.js
import LocalScheme from '@nuxtjs/auth/lib/schemes/local'
export default class CustomScheme extends LocalScheme {
_setToken (token) {
if (this.options.globalToken) {
// Set Authorization token for all axios requests
this.$auth.ctx.app.$axios.setHeader(this.options.tokenName, token)
}
}
_clearToken () {
if (this.options.globalToken) {
// Clear Authorization token for all axios requests
this.$auth.ctx.app.$axios.setHeader(this.options.tokenName, false)
}
}
mounted () {
if (this.options.tokenRequired) {
const token = this.$auth.syncToken(this.name)
this._setToken(token)
}
return this.$auth.fetchUserOnce()
}
async login (endpoint) {
if (!this.options.endpoints.login) {
return
}
// Get token
const result = await this.$auth.request({
...endpoint
},
this.options.endpoints.login
)
// Set token
if (this.options.tokenRequired) {
const token = this.options.tokenType
? this.options.tokenType + ' ' + result
: result
this.$auth.setToken(this.name, token)
this._setToken(token)
}
// If result I get and set user
if (result) {
const user = await this.$auth.request({
...endpoint
},
this.options.endpoints.user
)
this.$auth.setUser(user);
}
}
async fetchUser (endpoint) {
// User endpoint is disabled.
if (!this.options.endpoints.user) {
this.$auth.setUser({})
return
}
// Token is required but not available
if (this.options.tokenRequired && !this.$auth.getToken(this.name)) {
return
}
// Try to fetch user and then set
try{
const user = await this.$auth.requestWith(
this.name,
endpoint,
this.options.endpoints.login
)
this.$auth.setUser(user)
} catch (error){
console.log(error)
}
}
}
当我在 login() 方法中设置this.$auth.setUser(user)
时一切正常,应用程序将我重定向到/dashboard
页面,用户信息(如角色和电子邮件)显示在导航栏上,但是当我刷新页面时,我失去了用户数据。 该应用程序尝试 fetchUser 但它给了我 400 错误,因为用户和密码未发送。 我不明白的另一件事是为什么在async fetchUser (endpoint)
未定义endpoint
参数??? . 我觉得这部分有问题。
我希望你能帮助我
我只是删除了所有这些库并进行了自己的自定义 Nuxt 身份验证https://nemanjadragun92.medium.com/nuxt-js-custom-authentication-245d2816c2f3
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.