gpt4 book ai didi

javascript - (Nuxt.js/Vue.js) 在 Vuex 商店中设置 axios 身份验证 token 在刷新后重置

转载 作者:搜寻专家 更新时间:2023-10-30 22:13:06 25 4
gpt4 key购买 nike

我有以下商店代码来处理登录、注销、获取用户并将 token 设置为所有 axios 请求作为 auth header 。

它与客户端渲染配合得很好,比如我转到登录页面,登录,获取 token ,将其存储在 cookie 中。但是当我刷新页面时,似乎不再设置 token 了。我我在 NuxtServerInit 上调用 fetch 操作,仍然没有运气。我的代码在哪里失败有什么想法吗?

这是我的 store/index.js 文件:

https://jsfiddle.net/3dc07yv4/

import Cookie from 'cookie'
import Cookies from 'js-cookie'

export const state = () => ({
sidebar: true,
token: null,
user: null
})

export const mutations = {
// SET SIDEBAR
toggleSidebar (state) {
state.sidebar = !state.sidebar
},
// SET USER
setUser (state, user) {
state.user = user
},
// SET TOKEN
setToken (state, token) {
state.token = token
}
}

export const getters = {
loggedIn (state) {
return Boolean(state.user && state.token)
}
}

export const actions = {
async nuxtServerInit ({ dispatch }, { req }) {
await dispatch('fetch')
},
// Update token
async updateToken ({ commit }, token) {
// Update token in store's state
commit('setToken', token)
// Set Authorization token for all axios requests
console.log('Setting axios token to: ', token)
this.$axios.setToken(token, '')
// Update cookies
if (process.browser) {
// ...Browser
if (token) {
Cookies.set('ccmsToken', token, { expires: 1 })
} else {
Cookies.remove('ccmsToken')
}
} else {
// ...Server
let params = {
domain: '/'
}
if (!token) {
let expires
let date = new Date()
expires = date.setDate(date.getDate() + 1)
params.expires = new Date(expires)
}
this.app.context.res.setHeader('Set-Cookie', Cookie.serialize('ccmsToken', token, params))
}
},

// Fetch Token
async fetchToken ({ dispatch }) {
let token
// Try to extract token from cookies
if (!token) {
const cookieStr = process.browser ? document.cookie : this.app.context.req.headers.cookie
const cookies = Cookie.parse(cookieStr || '') || {}
token = cookies['ccmsToken']
}
if (token) {
await dispatch('updateToken', token)
}
},

// Reset
async reset ({ dispatch, commit }) {
commit('setUser', null)
await dispatch('updateToken', null)
},

// Fetch
async fetch ({ getters, state, commit, dispatch }, username = 'admin', { endpoint = 'http://localhost:8000/api/user' } = {}) {
// Fetch and update latest token
await dispatch('fetchToken')
// Skip if there is no token set
if (!state.token) {
return
}

// Try to get user profile
try {
const data = await this.$axios.$get(endpoint + '?username=' + username)
commit('setUser', data)
} catch (e) {
// Reset store
await dispatch('reset')
}
},

// Login
async login ({ dispatch }, { fields, endpoint = 'http://localhost:8000/api/login' } = {}) {
try {
// Send credentials to API
let data = await this.$axios.$post(endpoint, fields)
if (data.success) {
await dispatch('updateToken', data['token'])
// Fetch authenticated user
await dispatch('fetch', data.user.username)
} else {
throw new Error(data.message)
}
} catch (error) {
if (error.response && error.response.status === 401) {
throw new Error('Bad credentials')
}
throw error
}
},

// Logout
async logout ({ dispatch, state }) {
try {
await dispatch('reset')
} catch (e) {
console.error('Error while logging out', e)
}
}

}

最佳答案

我已经通过实现一个拦截器解决了这个问题,该拦截器将 token 注入(inject)到每个 axios 请求的 header 中。它看起来像这样:

export default ({ $axios, store }) => {
$axios.defaults.baseURL = 'https://api.com/api/'

if (process.server) {
return
}

$axios.interceptors.request.use(request => {
request.baseURL = 'https://api.com/api/'

// Get token from auth.js store
const token = store.state.token

// Update token axios header
if (token) {
request.headers.common['Authorization'] = token
}
return request
})
}

您将它用作 nuxt 插件。

关于javascript - (Nuxt.js/Vue.js) 在 Vuex 商店中设置 axios 身份验证 token 在刷新后重置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48402747/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com