Maurilei Aleixo
Maurilei Aleixo

Reputation: 1

apiResponse.data return null. What should I do, in Postman works normally

response just returns null, every time response is null, apiResponse.data return null, returns server error, What should I do. I need to pass to a list

apiResponse.data = jsonDecode(response.body)['posts']
                        .map((p) => Post.fromJson(p))
                        .toList();

Future<ApiResponse> getPosts() async {
  ApiResponse apiResponse = ApiResponse();
  try {
    String token = await getToken();
    final response = await http.get(Uri.parse(postsURL), headers: {
      'Accept': 'application/json',
      'Authorization': 'Bearer $token'
    });
    switch (response.statusCode) {
      case 200:
        apiResponse.data = jsonDecode(response.body)['posts']
            .map((p) => Post.fromJson(p))
            .toList();
        apiResponse.data as List<dynamic>;
        break;
      case 401:
        apiResponse.error = unauthorized;
        break;
      default:
        apiResponse.error = somethingWentWrong;
        break;
    }
  } catch (e) {
    apiResponse.error = serverError;
  }
  return apiResponse;
}

Upvotes: 0

Views: 59

Answers (1)

Sojuz
Sojuz

Reputation: 11

Does response only return null when the status code is 40*?

if yes.. try to see for yourself the exception that you're catching, it should almost always return "the headers can't be parsed" something like this, if this is the case, the http package from pub dev doesn't really handle parsing complex headers well..

refer to this Github issue.. https://github.com/dart-lang/sdk/issues/46442#issuecomment-463854487

Not really a backend dev, but apparently changing your www-authenticate header return might fix it.

Upvotes: 1

Related Questions