i want to access an api with angular. the api is hosted by pythonanywhere. When accessing the API I get the following error:
Access to fetch at 'https://www.pythonanywhere.com/api/v0/user/myusername/cpu/?format=json' 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. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.
data-analysis.component.ts:26 ERROR HttpErrorResponse {headers: HttpHeaders, status: 504, statusText: 'Gateway Timeout', url: 'https://www.pythonanywhere.com/api/v0/user/StevoEs/cpu/?format=json', ok: false, …}
python-anywhere.service.ts
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class PythonAnywhereService {
private host = 'www.pythonanywhere.com';
private username = 'myUsername';
private token = 'myToken';
constructor(private http: HttpClient) {}
getCpuData(): Observable<any> {
const headers = new HttpHeaders({
'Authorization': `Token ${this.token}`
});
return this.http.get<any>(
`https://${this.host}/api/v0/user/${this.username}/cpu/?format=json`,
{ headers }
);
}
}
data-analyse.component.ts
import { Component, OnInit } from '@angular/core';
import { PythonAnywhereService } from '../../services/python-anywhere.service';
import { HttpClient, HttpHeaders } from '@angular/common/http';
@Component({
selector: 'app-data-analyse',
template: `
<div class="card text-center bg-dark">
<div class="card-header">
Server CPU auslastung!
</div>
<div class="card-body">
<div *ngIf="cpuData">
{{ cpuData }}
</div>
</div>
</div>
`
})
export class DataAnalysisComponent implements OnInit {
cpuData: any;
constructor(private pythonAnywhereService: PythonAnywhereService) {}
ngOnInit() {
this.pythonAnywhereService.getCpuData().subscribe(data => {
this.cpuData = data;
});
}
}
I have read through the documentation on Angular. But I don't understand it. Searching in forums didn't help me either.
I have installed Django on pythonanywhere. There are some settings but I couldn't solve the problem there either.
I have censored the username and the token here.
Does anyone know what I can do?
edit:
i have tried everything i could think of. however, the errors do not change at all and i am getting stuck. here is my setting.py:
from pathlib import Path
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/4.0/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'django-insecure-b70$%5snd)0k!hfliophl)0b%s^kypxu0wfv!znvmw&d!7^7&7'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
CORS_ALLOW_ALL_ORIGINS: True
CORS_ORIGIN_ALLOW_ALL = True
CORS_ALLOWED_ORIGINS = [
"*",
"https://myhomepage.de",
"http://localhost:8080",
"http://127.0.0.1:9000",
"http://localhost:4200",
]
ALLOWED_HOSTS = ['StevoEs.pythonanywhere.com']
# Application definition
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 = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'corsheaders',
]
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',
]
ROOT_URLCONF = 'mysite.urls'
CORS_ALLOWED_ORIGINS = [
"*",
"http://read.only.com",
"http://change.allowed.com",
]
CSRF_TRUSTED_ORIGINS = [
"http://change.allowed.com",
]
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'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',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/4.0/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': BASE_DIR / 'db.sqlite3',
}
}
# Password validation
# https://docs.djangoproject.com/en/4.0/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/4.0/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/4.0/howto/static-files/
STATIC_URL = 'static/'
# Default primary key field type
# https://docs.djangoproject.com/en/4.0/ref/settings/#default-auto-field
DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField'
# default static files settings for PythonAnywhere.
# see https://help.pythonanywhere.com/pages/DjangoStaticFiles for more info
MEDIA_ROOT = '/home/StevoEs/mysite/media'
MEDIA_URL = '/media/'
STATIC_ROOT = '/home/StevoEs/mysite/static'
STATIC_URL = '/static/'```