jazzband / django-rest-knox

Authentication Module for django rest auth
MIT License
1.17k stars 213 forks source link

How do you make this work with `fetch(...)`? #234

Closed valexandersaulys closed 4 years ago

valexandersaulys commented 4 years ago

I've been at this and I'm still struggling.

Browser: Firefox 82.0 OS: Ubuntu 18.04

I've been trying to make requests using fetch which is built into javascript. I'm using create-react-app which is hosted on a separate URL from my Django backend. I have made sure to correct for CORS issues while I'm developing.

    fetch(`http://localhost:3001/api/v1/accounts/auth/login/`, {
      method: "POST",
      mode: "cors",
      headers: {
        Authorization: "Basic " + btoa("vincent:vincent")
      }
    })
      .then(res => res.json())
      .then(json => console.log(json))
      .catch(err => console.log(err));

But when I make the above request, I get this reply:

Unauthorized: /api/v1/accounts/auth/login/
[04/Nov/2020 01:10:28] "POST /api/v1/accounts/auth/login/ HTTP/1.1" 401 58

And on Firefox:

    fetch(`http://localhost:3001/api/v1/accounts/auth/login/`, {
      method: "POST",
      mode: "cors",
      headers: {
        Authorization: "Basic " + btoa("vincent:vincent")…
Promise { <state>: "pending" }

XHROPTIONShttp://localhost:3001/api/v1/accounts/auth/login/
[HTTP/1.1 401 Unauthorized 2ms]

Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3001/api/v1/accounts/auth/login/. (Reason: CORS preflight response did not succeed).

XHRPOSThttp://localhost:3001/api/v1/accounts/auth/login/

TypeError: NetworkError when attempting to fetch resource. debugger eval code:10:29
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:3001/api/v1/accounts/auth/login/. (Reason: CORS request did not succeed).

I did confirm that django requests do work so its not an issue of the request.

What in the world am I doing wrong?

Thanks, Vincent

valexandersaulys commented 4 years ago

I fixed this rather bizarre error. It's not very knox specific but I'll close this out and let anybody else who trips across what to do.

The fix (for me): Use Create-React-App's Proxying from package.json to proxy out to http://localhost:800 and use relative URLs for all fetch requests (e.g. /api/ as opposed to localhost:8000/api/). I gleaned this from this guide.

Firefox appears to play very strict with CORS issues and this only comes up in local development.