[英]Error in receiving data from the Django REST API
我有一个使用ionic2和Angularjs2制作的移动应用程序。
我在本地主机上运行Django,即http://127.0.0.1:8000/stocks/,此网址返回JSON数据,如下所示:
[
{
"id": 1,
"ticker": "FB",
"open": 7.0,
"close": 10.0,
"volume": 500
},
{
"id": 2,
"ticker": "AMZN",
"open": 125.05,
"close": 200.98,
"volume": 800
},
{
"id": 3,
"ticker": "MSFT",
"open": 1.25,
"close": 87.0,
"volume": 7000
}
]
我在应用程序中使用提供程序从URL获取数据
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class GetData {
public data:any;
constructor(public http: Http) {
console.log('Hello GetData Provider');
}
load(){
if (this.data) {
return Promise.resolve(this.data);
}
return new Promise(resolve => {
this.http.get('http://127.0.0.1:8000/stocks/')
.map(res => res.json())
.subscribe(data => {
this.data = data;
resolve(this.data);
});
});
}
}
我在页面中使用的此提供程序来接收数据并显示
import { Component } from '@angular/core';
import {GetData} from '../../providers/get-data';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public recvData:any;
constructor(public navCtrl: NavController, public getData: GetData) {
this.loadPeople();
}
loadPeople(){
this.getData.load()
.then(data => {
this.recvData = data;
});
console.log("the received data is >> ",this.recvData);
}
}
并像这样在我的HTML页面中使用它
<ion-content padding>
<ion-list>
<ion-item *ngFor='let stock of recvData'>
<p>stock.ticker</p>
</ion-item>
</ion-list>
</ion-content>
我收到此错误:
XMLHttpRequest cannot load http://127.0.0.1:8000/stocks/. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8100' is therefore not allowed access.
main.js:43460EXCEPTION:状态为0的URL响应:null
您需要在Django应用上启用CORS 。
您可以将django-cors-headers与Django结合使用。
安装软件包后,将http://localhost:8100
到白名单。
CORS_ORIGIN_WHITELIST = (
'localhost:8100',
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.