我的后端是由 Django-Rest-Framework 提供的 REST API。我在前端使用 VueJS,并试图找出进行身份验证/登录的最佳实践。这可能是糟糕的代码,但它可以工作(在一个名为 Login.vue
的组件中):
methods: {
login () {
axios.post('/api-token-auth/login/', {
username: this.username,
password: this.pwd1
}).then(response => {
localStorage.setItem('token', response.data.token)
}).catch(error => {
console.log("Error login")
console.log(error)
})
this.dialog = false
}
}
使用
localStorage
有意义吗?这边走?另外,我想知道用户什么时候想退出,我调用 /api-token-auth/logout
,我还需要从 localStorage
中删除 token 吗? ?我实际上并不清楚 Django 端或浏览器/Vue 上的 token 发生了什么。
最佳答案
应用程序范围的数据,例如身份验证和用户信息,应该进入集中状态。您可以使用 Vuex 或 a simple shared state . Vuex 很棒,但它确实增加了复杂性,所以你必须计算成本。如果你使用Vuex,你可以使用Vuex persisted state将其保存在本地存储中。这应该比 localStorage 访问快得多。以我的经验,localStorage 不可靠,可能会导致问题。国家是要走的路。
例如,修改您当前的代码以将其发送到 Vuex:
methods: {
login () {
axios.post('/api-token-auth/login/', {
username: this.username,
password: this.pwd1
}).then(response => {
that.$store.commit('LOGIN_SUCCESS', response)
}).catch(error => {
console.log("Error login")
console.log(error)
})
this.dialog = false
}
}
然后在 Vuex 中(如/store/modules/user.js 如果使用模块):
Vue.use(Vuex)
const state = { token: null}
const mutations = {
LOGIN_SUCCESS(state, response) {
state.token = response.token
}
export default {
state,
mutations
}
并通过 Getter 或直接调用 token :
this.$store.state.user.token
这假设 Vue 使用了 store。例如,在 main.js 中,您将拥有:
import store from './store/index.js'
new Vue({
el: '#app',
store
})
关于django - 在 VueJS 中存储身份验证 token 的最佳实践?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45384172/