【问题标题】:Access to XMLHttpRequest at .' from origin . has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present访问 XMLHttpRequest 在。从原产地。已被 CORS 策略阻止:不存在“Access-Control-Allow-Origin”标头
【发布时间】:2021-04-03 21:12:47
【问题描述】:

我使用 Django 构建我的 API 并尝试从 Angular 使用这个 API,但我得到一个 CORS 策略错误。 下面是我的代码。由于我是 Django 和 Angular 的新手,如果有人能帮助我解决这个问题,我将不胜感激。

Django 设置.py

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'bd_api',
    'rest_auth',
    'rest_framework.authtoken' ,
    'django.contrib.sites' ,
    'allauth' ,
    'allauth.account',
    'rest_auth.registration',
    'django_filters',
    'corsheaders' ,
    ]
CORS_ALLOW_CREDENTIALS = True
ALLOWED_HOSTS = ['*']

CORS_ALLOWED_ORIGINS = [
    'http://localhost:4200',
]
SITE_ID = 1

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

Angular 代码文件

环境.ts

export const environment = {
  production: false,
  api_url: "http://127.0.0.1:8000/op-api"
};

intercept.ts

import { Injectable } from '@angular/core';
import {
  HttpRequest,
  HttpHandler,
  HttpEvent,
  HttpInterceptor,
  HttpHeaders
} from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable()
export class HttpHeaderInterceptor implements HttpInterceptor {

  constructor() {}

  intercept(request: HttpRequest<unknown>, next: HttpHandler): Observable<HttpEvent<unknown>> {
const headers = new HttpHeaders({
  // 'Access-Control-Allow-Origin': '*',
  'Accept': 'application/json',
});
const reqWithToken = request.clone({headers});
return next.handle(reqWithToken);

}
}

http.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { environment } from '../../environments/environment';

@Injectable({
  providedIn: 'root'
})
export class HttpserviceService {

  baseUrl = environment.api_url;
  // headers = {Authorization: true}
  constructor(private http: HttpClient) { }

  public getContries(cond=''){
    if(cond != '')
      return this.http.get(this.baseUrl+'/country?'+cond);
    else
      return this.http.get(this.baseUrl+'/country');
  }
}

从我的 main.component.ts 中的这个方法调用 api

constructor(private fb: FormBuilder, private httpService: HttpserviceService) { }

this.httpService.getContries().subscribe((resp) =>{
      console.log('getcontriessss', resp);
      if(resp['result'].length > 0){
        this.dropdownOptions = [];
        resp['result'].forEach(element => {
          this.dropdownOptions = [...this.dropdownOptions, {id: element.short_name, name: element.name}]
        });
      }else{

      }
    });

但我收到此错误。

Access to XMLHttpRequest at 'http://127.0.0.1:8000/op-api/country' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
zone.js:3324 GET http://127.0.0.1:8000/op-api/country net::ERR_FAILED
core.js:4127 ERROR 
HttpErrorResponse {headers: HttpHeaders, status: 0, statusText: "Unknown Error", url: "http://127.0.0.1:8000/op-api/country", ok: false, …}
error: ProgressEvent {isTrusted: true, lengthComputable: false, loaded: 0, total: 0, type: "error", …}
headers: HttpHeaders {normalizedNames: Map(0), lazyUpdate: null, headers: Map(0)}
message: "Http failure response for http://127.0.0.1:8000/op-api/country: 0 Unknown Error"
name: "HttpErrorResponse"
ok: false
status: 0
statusText: "Unknown Error"
url: "http://127.0.0.1:8000/op-api/country"
__proto__: HttpResponseBase

我试图找出解决方案,但不明白问题出在哪里。是来自我的 Django 文件还是 Angular 文件。

【问题讨论】:

    标签: django angular api


    【解决方案1】:

    对于开发,您只需将代理配置添加到您的package.jsonwebpack.config.js。不需要corsheaders。此外,您可以在浏览器中使用一些扩展程序或禁用安全性,但不建议这样做。对于部署,这取决于您希望如何部署您的应用程序。如果两者都在同一个端口上运行,则没有问题。

    【讨论】:

      【解决方案2】:

      我认为将CORS_ORIGIN_ALLOW_ALL = True 行添加到您的settings.py 可能会解决您的问题。但在您的生产设置中要小心。也许将以下内容添加到您的 settings.py 是一种更安全的方式:

      if settings.DEBUG:
          CORS_ORIGIN_ALLOW_ALL = True
          INSTALLED_APPS.append(
              'corsheaders'
          ) # if you haven't this app in your installed apps
          MIDDLEWARE.append(
              'corsheaders.middleware.CorsMiddleware',
          ) # if you haven't this app in your installed apps
      

      因此,通过更改项目的调试模式,cors 设置也将无效。

      【讨论】:

      • 出于测试目的,即使添加 CORS_ORIGIN_ALLOW=True 也不会消除错误,我仍然会收到错误
      • 你能把CORS_ORIGIN_ALLOW_ALL = True 移动到settings.py 的末尾,看看它是否有效?完成此操作后请重新启动您的服务器。
      • 确保它是CORS_ORIGIN_ALLOW_ALL = True 而不是CORS_ORIGIN_ALLOW=True
      • 我按照你的指示做了,但还是看到了错误。
      【解决方案3】:

      使用 CORS_ORIGIN_WHITELIST

      # ============= Cores Header Origin ====================
          
          CORS_ALLOW_CREDENTIALS = True
          
          CORS_ORIGIN_WHITELIST = (
              'http://localhost:4200',
              'http://localhost:8000'
          )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-30
        • 1970-01-01
        • 2019-08-09
        • 2022-09-27
        • 2021-03-27
        • 2019-08-10
        • 2020-04-15
        • 2021-02-01
        相关资源
        最近更新 更多