Angular error with json API with python anywhere- has been blocked by CORS
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?
This is not a front-end (Angular) issue. You've been blocked by CORS. More details are available here: CORS MOZILLA and the solution to your question is probably provided here: SOLUTION. I know it's not a much of an answer, but at this point I would just copy someone else. It's no point if I can just provide a link.