Ionic and Django: No 'Access-Control-Allow-Origin' header is present

I'm building my first app with Ionic and I'm using Django Rest Framework as API.

I just want to create a simple page in Ionic that shows a list of categories.

I've created the model Category, and the ViewSets for the API. When I go to the Django-rest-framwork viewer (http://localhost:3010/category/) everything works fine.

But when I try to get the results (with Ionic) I get this error:

XMLHttpRequest cannot load http://localhost:3010/category/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.

My code:

import {Page, Platform, NavController} from 'ionic/ionic';
import {EmployeeDetailsPage} from '../employee-details/employee-details';
import {Http} from 'angular2/http';

@Page({
  templateUrl: 'build/pages/getting-started/getting-started.html'
})
export class GettingStartedPage {
  constructor(platform: Platform, nav: NavController, http: Http) {
    this.platform = platform;
    this.nav = nav;
    this.http = http;

    this.http.get("http://localhost:3010/category/")
        .subscribe(data =>{
          this.items=JSON.parse(data._body).results;//Bind data to items object  
        },error=>{
            console.log(error);// Error getting the data
        } );

  }

}

Answers


You need to send CORS headers to Ionic Framework to let cross-domain ajax work, since your ionic app is hosted on port 8100, and django-server is running on port 3010, this is considered a cross-domain request.

For django, install CORS headers app through pip.

In your settings, enable 'corsheaders' app, and also add the allowed urls.

# this disables Cross domain requests
CORS_ORIGIN_ALLOW_ALL = False 

# this allows cookie being passed cross domain    
CORS_ALLOW_CREDENTIALS = True 

# this is the list of allowed origins for cross domain ajax
CORS_ORIGIN_WHITELIST = ( 
        'localhost:8100',

)

You may need to install CORS.

If you are testing on chrome you might also need to allow cross origin (There is an extension for it) which should get you around the CORS issue.


Need Your Help

What is the standard procedure used for login-systems in iOS-apps?

ios objective-c security authentication encryption

I am creating an app and a website for a project I've got going, but I'm not sure what I should do about login. This is not a "I'm a noob and I want an app with login"-question. I am somewhat exper...