【问题标题】:Error in receiving data from the Django REST API从 Django REST API 接收数据时出错
【发布时间】:2017-03-16 18:08:30
【问题描述】:

我有一个使用 ionic2 和 Angularjs2 制作的移动应用。

我在本地主机上运行我的 Django,即http://127.0.0.1:8000/stocks/ 此 url 返回 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

【问题讨论】:

标签: python django angular ionic-framework ionic2


【解决方案1】:

您需要在您的 Django 应用上启用CORS

您可以将 django-cors-headers 与 Django 一起使用。

安装包后将http://localhost:8100添加到白名单。

CORS_ORIGIN_WHITELIST = (
    'localhost:8100',
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-11-08
    • 2021-09-25
    • 1970-01-01
    • 1970-01-01
    • 2017-11-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多