Janik Spies
Janik Spies

Reputation: 427

CORS-Error when using django as backend for ionic app

I'm using Django Rest Framework as a backend for my Ionic app. I set up the API with JWT and with postman everything works fine. As soon as I try making a API call from my Ionic app I get the following error messages:

Error 1 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.mywebsite.com/api/movies. (Reason: header ‘password’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response).

Error 2 Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://www.mywebsite.com/api/movies. (Reason: CORS request did not succeed).

I run my django app on a apache2 webserver.

django-cors-headers is installed,
added to installed_apps,
added to the middleware and CORS_ORIGIN_ALLOW_ALL = Ture

In my Ionic app the request looks like this:

Service

fetchMovies() {

  const httpOptions = {
    headers: new HttpHeaders({
      'Content-Type':  'application/json',
      'Authorization': `Bearer ${this.authService.getToken()}`,
      'username': 'USERNAME',
      'password': 'PASSWORD'

    })
  }

    return this.http.get(this.url, httpOptions).pipe(tap(resData => {
      console.log(resData);
    }));
  }

I get the token like this:

 getToken() {
    return this.http.post('https://www.mywebsite.com/api-token', this.params);
  }

And I use the service as follows:


ionViewWillEnter() {
    this.moviesServcie.fetchMovies().subscribe();
  }

Does anyone have an idea what I'm doing wrong? If you need more information feel free to write a comment! Thanks in advance for any help

Upvotes: 2

Views: 641

Answers (1)

Jain Bhavesh
Jain Bhavesh

Reputation: 578

You need to use ionic native plugin here is the link below

https://ionicframework.com/docs/native/http

Upvotes: 2

Related Questions