5

I created a login API using Django rest framework and then used session auth. When i sent request via Postman , i get csrftoken and sessionid cookies. and i was able to access content on backend. OK fine.


But when i built small login form html and called that API for logging in. It worked. I see COOKIES IN RESPONSE BUT COOKIES ARE NOT SET IN CHROME BROWSER. Under Storage section in dev tools cookies are empty. when i tried to access content(other views/apis) , i was not able to.. I think its because of Cookies are not being stored in browser.. Been on this like 5 days. Please can Someone explain about cookies not being saved.?

View.py

class Login(APIView):
    authentication_classes = [SessionAuthentication,]

    def post(self, request, format=None):

        username = request.POST.get("username", "")
        print(request.session)
        password = request.POST.get("password", "")
        user = authenticate(request,username=username,password=password)
        if user is not None:
            login(request,user)
            print(user)

            return Response('Yes')
        else :
            return Response('No')

class List(APIView):
   authentication_classes = [SessionAuthentication,]
   permission_classes = [IsAuthenticated,]
   def get(self, request, format=None):
      return Response("Ark")

My Axios Request for login :

let s = this;
    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
    myHeaders.append("Authorization", "Basic cjox");
myHeaders.append("Access-Control-Allow-Credentials","*");

    var urlencoded = new URLSearchParams();


    var requestOptions = {
      method: 'POST',
      credentials: 'same-origin',
      headers: myHeaders,
      body: urlencoded,
      redirect: 'follow'
    };

    axios.post("http://127.0.0.1:8000/api/login/",urlencoded,{headers:myHeaders},{withCredentials: true})
    .then(res=>{
      console.log(res.headers);

    })

My other request :

var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/x-www-form-urlencoded");
myHeaders.append("Access-Control-Allow-Credentials","*");
    var urlencoded = new URLSearchParams();

    var requestOptions = {
      method: 'GET',
      credentials: 'same-origin',
      headers: myHeaders,
      redirect: 'follow'
    };

    axios.get("http://127.0.0.1:8000/api/d/",{headers:myHeaders},{withCredentials: true});
beg_dev
  • 93
  • 7

0 Answers0