在我的virtualenv中使用AJAX进行API调用时,我突然出现以下错误(第三方API,我不控制该服务器),并且已经研究了一堆关于类似问题的SO线程,但未成功:
Access to XMLHttpRequest at 'http://www.api-football.com/demo/api/v2/teams/team/77/' from origin 'http://127.0.0.1:8000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
我运行最新的Python + Django和Google Chrome版本。
我已经尝试过的:
CORS_ORIGIN_ALLOW_ALL = True
和CORS_ALLOW_CREDENTIALS = True
jquery.min.js:2 Cross-Origin Read Blocking (CORB) blocked cross-origin response https://api.footystats.org/league-teams?key=example&include=stats&league_id=1625&callback=jQuery34101697774297755965_1570102531537&_=1570102531538 with MIME type application/json. See https://www.chromestatus.com/feature/5629709824032768 for more details.
我的设置。py
ALLOWED_HOSTS = ['127.0.0.1']
SILENCED_SYSTEM_CHECKS = [
'admin.E408',
'admin.E409',
'admin.E410',
]
DEBUG = 'TRUE'
#Rooting
ROOT_URLCONF = 'dasocc_site.urls'
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, "static/")
#Applications
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOW_CREDENTIALS = True
CORS_ALLOW_METHODS = [
'DELETE',
'GET',
'OPTIONS',
'PATCH',
'POST',
'PUT',
]
CORS_ALLOW_HEADERS = [
'accept',
'accept-encoding',
'authorization',
'content-type',
'dnt',
'origin',
'user-agent',
'x-csrftoken',
'x-requested-with',
]
INSTALLED_APPS = [
'corsheaders',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'dasocc_app',
'dasocc_blog',
'dasocc_about',
]
#TEMPLATES
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': ['/DASOCC_SITE/templates'],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
#Middleware
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',
]
这是我的AJAX呼叫:
[..]
$.ajax({
method: "GET",
url: "https://api.footystats.org/league-teams?key=example&include=stats&league_id=1625",
success: function(response) {
console.log(response)
}
});
});
注意:当我在视图函数中使用相同的API网址进行调用时,它运行正常
Views.py API调用
def team_update(request):
team_id = request.GET.get('team')
response = requests.get(f'https://api.footystats.org/league-teams?key=example&include=stats&league_id=1625')
team_data = response.json()
以及相应的Chrome标头/错误。
..和IE