Eva*_*mir 10 authentication django django-rest-framework vuejs2
我的后端是由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
}
}
Run Code Online (Sandbox Code Playgroud)
使用localStorage
这种方式有意义吗?此外,我想知道用户何时想退出,我打电话/api-token-auth/logout
,我是否还需要从中删除令牌localStorage
?实际上,我不清楚Django端或者浏览器/ Vue上的令牌是什么.
For*_*ame 11
应用程序范围的数据(例如身份验证和用户信息)应进入集中状态.您可以使用Vuex或简单的共享状态.Vuex很棒,但它确实增加了复杂性,所以你必须计算成本.如果使用Vuex,则可以使用Vuex持久状态将其保留在localStorage中.这应该比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
}
}
Run Code Online (Sandbox Code Playgroud)
然后在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
}
Run Code Online (Sandbox Code Playgroud)
并通过Getter或直接调用令牌:
this.$store.state.user.token
Run Code Online (Sandbox Code Playgroud)
这假设存储由Vue使用.例如,在main.js中你将拥有:
import store from './store/index.js'
new Vue({
el: '#app',
store
})
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7193 次 |
最近记录: |