Can't login with Django Knox using Fetch POST request

239 views Asked by At

I'm trying to login from the react front end via a Fetch POST request to the Knox endpoint but I am unable to. I can login normally from http://localhost:8000/api/login/ so I assume something must be wrong with my fetch but I can't figure it out. On the Knox docs it says that the LoginView only accepts an empty body so I can't just put the login info in there either.

View (copy pasted from the docs and I added BasicAuthentication)

class LoginAPI(KnoxLoginView):
    permission_classes = (permissions.AllowAny,)
    authentication_classes = [BasicAuthentication]

    def post(self, request, format=None):
        serializer = AuthTokenSerializer(data=request.data)
        serializer.is_valid(raise_exception=True)
        user = serializer.validated_data['user']
        login(request, user)
        return super(LoginAPI, self).post(request, format=None)

Fetch:

const handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    const credentials = btoa(`${data.get('username')}:${data.get('password')}`);

    const requestOptions = {
            method: "POST",
            headers: {
                'Accept': 'application/json, text/plain, */*',
                'Content-Type': 'application/json',
                "Authorization": `Basic ${credentials}`
            },
            body: JSON.stringify({})

        }
     fetch('http://127.0.0.1:8000/api/login/', requestOptions)
            .then(response => console.log(response))
            .catch(error => console.log(error))

Would appreciate any help as to what I'm doing wrong here

0

There are 0 answers