简体   繁体   中英

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 stacked the middleware in this way:

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'corsheaders.middleware.CorsMiddleware', #CORS middleware
    'users.middleware.AuthenticationMiddleware', #custom middleware for jwt
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
]

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.

There you have a screenshot of preflight request and response from browser's.network tab:

预检请求标头

预检响应头 1

预检响应标头 2

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

'Access-Control-Allow-Origin' : '*'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM