Reputation: 7170
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
} );
}
}
Upvotes: 0
Views: 1384
Reputation: 43235
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',
)
Upvotes: 3