Django built-in login failed from react

django

@method_decorator(csrf_exempt, name='dispatch')
class UserLoginView(GenericAPIView):
    permission_classes = (AllowAny,)
    serializer_class = UserLoginSerializer

    def post(self, request):
        serializer = self.serializer_class(data=request.data)
        user = serializer.validate(request.data)

        if user is None:
            return Response(status=status.HTTP_400_BAD_REQUEST)
        else:
            user.before_last_login = user.last_login
            login(request, user)
            user.save()
            user = UserSerializer(user)
            return Response(data={'id': user.data['id'], 'img': user.data['image']}
                            , status=status.HTTP_200_OK)

react

const res = await axios.post(`${APIURL}/account/login/`, {
  id: id,
  password: pwd,
});

when I try to login from react, I get suceessful response( Response(data={'id': user.data['id'], 'img': user.data['image']}, status=status.HTTP_200_OK) ) but failes, still user is annonymousUser in django. How can I fix this error?

I'm guessing your React frontend is hosted on a different server. The login() method just adds the user's session id to the browser storage and then uses middleware to attach this session id to requests.

If your React frontend is hosted on a different server, it will have no knowledge of this session cookie and it will not be appended to your axios() requests. Instead you need add the users token (if using token based authentication) to your Response() and cache this in your browser. You can then append this token in subsequent axios() calls which will identify the user to your Django backend.

Back to Top