Angular&Django: No 'Access-Control-Allow-Origin' header is present on the requested resource

I'm learning how to develop a website using Angular and Django. I got this error from my Angular localhost:

Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/user/' from origin 
'http://localhost:4200' has been blocked by CORS policy: Response to preflight request 
doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

In django's settings.py I have installed a custom users app, rest_framework and corsheaders app Besides that, I have included this config:

CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True

I've got no CORS errors with login and register requests from my angular app but the problem appeared when I used a middleware to check if a jwt header had been supplied (and test if it was valid or if it had expired). I added that middleware to settings.py file and that request worked fine in Postman so I tried to implement it from Angular.

This is the method:

validateToken(): Observable<boolean> {
    const url = `${this.baseUrl}/user/`;
    const headers = new HttpHeaders().set(
      'jwt',
      localStorage.getItem('token') || ''
    );
    return this.http
      .get<AuthResponse>(url, {
        headers,
      })
      .pipe(
        map((resp) => {
          localStorage.setItem('token', resp.jwt);
          this._user = resp.user;
          return resp.ok;
        }),
        catchError((err) => of(false))
      );

However, I'm getting the error I showed before. Have any of you gone through this same problem with Angular and Django before and know how it could be solved?

PS: I've tried to install 'Allow CORS: Access-Control-Allow-Origin' Chrome extension but when I used it I still got this error:

 Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/user/' from origin 'http://localhost:4200' 
 has been blocked by CORS policy: Response to preflight request doesn't pass access control check: 
 It does not have HTTP ok status.

On your headers variable you need to set a pair of property:value containing the missing access control property:

'Access-Control-Allow-Origin' : '*'
Back to Top