无法在DRF API上使用AJAX调用设置Cookie

时间:2019-03-07 11:51:53

标签: ajax django-rest-framework

我有一个Django Rest API,它在响应对象中设置cookie。当我点击浏览的API时,浏览器将cookie存储在Application> Cookies下。当我尝试使用AJAX调用重现相同的结果时,cookie不会自动存储。尽管我在AJAX调用中确实获得了响应对象。

我的代码如下

views.py

class UserLogin(generics.GenericAPIView):
    serializer_class = serializers.UserLoginSerializer
    permission_classes = (
        permissions.AllowAny,
    )

    def finalize_response(self, request, *args, **kwargs):
        """
        Set Authorization in cookie.
        """
        response_obj = super(UserLogin, self).finalize_response(
            request, *args, **kwargs)
        if request.POST and response_obj.status_code == 200:
            response_obj['Authorization'] = 'Token '\
                + response_obj.data['auth_token']
            print 'COOKIE NOT SET'
            response_obj.set_cookie(
                'Authorization', response_obj['Authorization'])
            print 'COOKIE SET'
        return response_obj

    def post(self, request):
        """
        If serializer is valid.
            - call action.
        """
        serializer = self.get_serializer(
            data=request.data)
        if serializer.is_valid():
            user = serializer.validated_data.get('user')
            token, boolean = Token.objects.get_or_create(user=user)
            if not boolean:
                token.created = datetime.datetime.now()
                token.save()
            # user.login_attempts = 0
            user.save()
           data = serializers.TokenSerializer(token).data
            return response.Response(
                data=data,
                status=status.HTTP_200_OK,)
        return response.Response(
            data=serializer.errors,
            status=status.HTTP_400_BAD_REQUEST)

serializers.py

class UserLoginSerializer(serializers.Serializer):

    def __init__(self, *args, **kwargs):
        super(UserLoginSerializer, self).__init__(*args, **kwargs)
        self.user = None
        self.fields[User.USERNAME_FIELD] = serializers.CharField()

    password = serializers.CharField(
        style={'input_type': 'password'})

    def validate(self, data):
        username = data.get(User.USERNAME_FIELD).lower()
        password = data.get('password')

        try:
            user = User.objects.get(username=username)
        except:
            raise serializers.ValidationError(
                messages.INVALID_CREDENTIALS_ERROR)
        data['user'] = user
        user_service = UserService()
        is_valid = user_service.verify_account(user, password)
        if not is_valid:
            raise serializers.ValidationError(
                messages.INACTIVE_ACCOUNT_ERROR)
        return data

    class Meta:
        fields = (User.USERNAME_FIELD, 'password')

ajax通话

$(document).ready(function() {

   $('form').submit(function(event) {


       var formData = {
           'username'              : $('input[name=username]').val(),
           'password'             : $('input[name=password]').val(),

       };

       // process the form
       $.ajax({
           type        : 'POST', 
           url         : 'http://13.232.122.165/users/login/', 
           data        : formData, 
           dataType    : 'json', 
           encode          : true
       })
           // using the done promise callback
           .done(function(data) {

               // log data to the console so we can see
               console.log(data); 
               location.href = "localhost:5000/profile"
               // here we will handle errors and validation messages
           });

       // stop the form from submitting the normal way and refreshing the page
       event.preventDefault();
   });

});

1 个答案:

答案 0 :(得分:0)

该Cookie已附加,但是除非您位于请求url域上,否则您无法从开发人员工具中看到它。 尝试使用ajax登录并在浏览器中点击请求网址(任意端点),您将看到cookie。