D:\VueShop\online-store\src\api\api.js
//登录
export const login = params => {
return axios.post(`${host}/login/`, params)
}
和我们之前定义的不一样:
需要修改后台定义的
# jwt的认证接口
# url(r'^jwt_auth/', obtain_jwt_token),
url(r'^login/', obtain_jwt_token),
把 host 改为:local_host
看效果:
启动前端项目,登录
登录成功:
看一下原理:
methods:{
login(){
// if(this.userName==''||this.parseWord==''){
// this.error = true;
// return
// }
var that = this;
login({
username:this.userName, //当前页码
password:this.parseWord
}).then((response)=> {
console.log(response);
//本地存储用户信息
cookie.setCookie('name',this.userName,7);
cookie.setCookie('token',response.data.token,7)
//存储在store
// 更新store数据
that.$store.dispatch('setInfo');
//跳转到首页页面
this.$router.push({ name: 'index'})
})
.catch(function (error) {
if("non_field_errors" in error){
that.error = error.non_field_errors[0];
}
if("username" in error){
that.userNameError = error.username[0];
}
if("password" in error){
that.parseWordError = error.password[0];
}
});
先安装插件: vue.js devtools
按 F12
D:\VueShop\online-store\src\store\mutations.js
现在来个新技能
C:\Users\huang\PycharmProjects\MxShop\apps\users\views.py
from django.shortcuts import render
# Create your views here.
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth import get_user_model
from django.db.models import Q
User = get_user_model()
class CustomBackend(ModelBackend):
"""
自定义用户验证
"""
def authenticate(self, request, username=None, password=None, **kwargs):
try:
user = User.objects.get(Q(username=username)|Q(mobile=username))
if user.check_password(password):
return user
except Exception as e:
return None
配置一下:
C:\Users\huang\PycharmProjects\MxShop\MxShop\settings.py
AUTHENTICATION_BACKENDS = (
'users.views.CustomBackend',
)
看一下有没有效果:
先打个断点:
确实进入了
神奇!!!
下面设置过期时间:
JWT_AUTH = {
'JWT_EXPIRATION_DELTA': datetime.timedelta(days=7),
'JWT_AUTH_HEADER_PREFIX': 'JWT',
}