1、在使用VUE.js进行用户认证时,可以使用RESTful,reqwest.js,Cookie.js进行操作。
logIn:function () {
var self = this;
reqwest({
url:'/api/token-auth',
type:'json',
method:'post',
data:{
username:'admin',
password:'admin12345',
},
success:function (resp) {
console.log(resp);
Cookies.set('token',resp.token);
self.getData()
},
})
},
其中/api/token-auth
,为token-auth验证url,在urls.py中
引入from rest_framework.authtoken import views
,urlpattern写入url(r'^api/token-auth$', views.obtain_auth_token),
2、在后台引入相应的库文件
from rest_framework.decorators import api_view, authentication_classes
from rest_framework.authentication import TokenAuthentication #认证库
class VideoSerializer(serializers.ModelSerializer):
title = serializers.CharField(min_length=1)
class Meta:
model = Video
fields = '__all__'
depth = 1
@api_view(['GET', 'POST'])
@authentication_classes((TokenAuthentication, )) #装饰器
def video(request):
video_list = Video.objects.order_by('-id')
if request.method == 'GET':
print(request.user)
print(request.auth)
serializer = VideoSerializer(video_list, many=True)
return Response(serializer.data)
elif request.method == 'POST':
serializer = VideoSerializer(data=request.data)
if serializer.is_valid():
serializer.save()
return Response(serializer.data, status=status.HTTP_201_CREATED)
body = {
'body': serializer.errors,
'msg': '40001'
}
return Response(body, status=status.HTTP_400_BAD_REQUEST)
3、在前台刷新得到信息时
getData:function () {
var self = this;
reqwest({
url:'/api/videos/',
type:'json',
headers:Cookies.get('token')? {'Authorization': 'Token ' + Cookies.get('token')}:{},
success:function (resp) {
console.log(resp);
self.vids = resp
},
})
},
其中headers部分是发送数据:
headers:Cookies.get('token')? {'Authorization': 'Token ' + Cookies.get('token')}:{},
即得到Token则发送认证,没有数据则发送空值。