【问题标题】:angulardart and django_rest. unable to get data from the backendangulardart 和 django_rest。无法从后端获取数据
【发布时间】:2020-02-09 17:22:11
【问题描述】:

this example is from a tutorial 我得到一个错误 异常:服务器错误;原因:需要一个“int”类型的值,但得到一个“String”类型的值

终端pycharm后端给出数据码200

[2020 年 2 月 9 日 11:45:48]“GET /adverts/HTTP/1.1”200 492

  class Hero {
  final int id;
  String name;

  Hero(this.id, this.name);

  factory Hero.fromJson(Map<String, dynamic> hero) =>
      Hero(_toInt(hero['id']), hero['name']);

  Map toJson() => {'id': id, 'name': name};
}

int _toInt(id) => id is int ? id : int.parse(id);

import 'dart:async';
import 'dart:convert';

import 'package:http/http.dart';

import 'hero.dart';

class HeroService {
  static final _headers = {'Content-Type': 'application/json'};
  static const _heroesUrl = 'http://127.0.0.1:8000/heroes'; // URL to 
 web API
  final Client _http;

  HeroService(this._http);

  Future<List<Hero>> getAll() async {
    try {
      final response = await _http.get(_heroesUrl);
      final heroes = (_extractData(response) as List)
          .map((value) => Hero.fromJson(value))
          .toList();
      return heroes;
    } catch (e) {
      throw _handleError(e);
    }
  }

  Future<Hero> create(String name) async {
    try {
      final response = await _http.post(_heroesUrl,
          headers: _headers, body: json.encode({'name': name}));
      return Hero.fromJson(_extractData(response));
    } catch (e) {
      throw _handleError(e);
    }
  }

  dynamic _extractData(Response resp) => json.decode(resp.body)['data'];

  Exception _handleError(dynamic e) {
    print(e); // for demo purposes only
    return Exception('Server error; cause: $e');
  }
}

【问题讨论】:

    标签: django http django-rest-framework


    【解决方案1】:

    我没有 json this -> data: 并从字符串中获取您需要的数据 -> dynamic _extractData (Response resp) => json.decode (resp.body) ['data'] ;删除 ['data'] 或编辑 JSON 生成 django_rest,如果您有关于如何在 drf 中获取类似 {'data':[ ]} 的 JSON 的信息,我很高兴阅读它

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-01-23
      • 1970-01-01
      • 2022-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-04
      • 2013-11-22
      相关资源
      最近更新 更多