且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

AngularJS + Django Rest Framework + CORS(CSRF Coo​​kie 没有出现在客户端)

更新时间:2023-11-08 11:57:22

所以我找到了自己的解决方案,似乎效果很好.

So I found my own solution to this, seems to work great.

这是我的代码的新片段:

This is the new snippets of my code:

class LoginView(APIView):

renderer_classes = (JSONPRenderer, JSONRenderer)

@method_decorator(ensure_csrf_cookie)
def post(self, request, format=None):
    c = {}
    c.update(csrf(request))
    serializer = LoginSerializer(data=request.DATA)

    if serializer.is_valid():
        userAuth = authenticate(username=serializer.data['username'], password=serializer.data['password'])

        if userAuth:

            if userAuth.is_active:
                login(request, userAuth)

                loggedInUser = AuthUserProfile.objects.get(pk=1)
                serializer = UserProfileSerializer(loggedInUser)

                user = [serializer.data, {'isLogged': True}]



        else:
            user = {'isLogged': False}

        return Response(user, status=status.HTTP_200_OK)

    return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)

AngularJS 客户端(在请求头中添加令牌)

$http.defaults.headers.post['X-CSRFToken'] = $cookies.csrftoken;

服务器端设置文件(专门针对 django-cors-headers)

默认添加前5个,但您需要添加X-CSRFToken"以允许使用CORS从客户端到API的此类标头,否则帖子将被拒绝.

CORS_ALLOW_HEADERS = (
'x-requested-with',
'content-type',
'accept',
'origin',
'authorization',
'X-CSRFToken'

)

就是这样!