1

I am trying to fetch data from Django backend in a Flutter web app. My Flutter program runs successfully, but it can't fetch data. If I print snapshot then it's showing XMLHttpRequest error. I tried disabling chrome web security according to this, but it's still not working.

file: fetch_data.dart

import 'package:http/http.dart' as http;

const baseUrl = 'http://localhost:8000/api/student/';

class Student {
  final id;
  final name;
  final email;

  Student(this.id, this.name, this.email);

  factory Student.fromJSON(Map<String, dynamic> json) {
    return Student(json['id'], json['name'], json['email']);
  }
}

Future<Student> fetchAllData() async {
  final response = await http.get(Uri.parse(baseUrl));

  if (response.statusCode == 200) {
    return Student.fromJSON(jsonDecode(response.body));
  } else {
    throw Exception('Failed to load data');
  }
}

file: homepage.dart

import 'package:flutter/material.dart';
import '../backend/fetch_data.dart';


class HomePage extends StatefulWidget {
  const HomePage({Key? key}) : super(key: key);

  @override
  State<HomePage> createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
  late Future<Student> studentData;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    studentData = fetchAllData();
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: FutureBuilder<Student>(
          future: studentData,
          builder: (context, snapshot) {
            print(snapshot);
            if (snapshot.hasData) {
              return Text(snapshot.data.toString());
            }
            else {
              return const Text('Some error occured');
            }
          },
        ),
      ),
    );
    
  }
}

Debug console when printing snapshot:

packages/http/src/browser_client.dart 69:22                                                                                    <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/zone.dart 1685:54                                              runUnary
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 147:18                                        handleValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 766:44                                        handleValueCallback
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 795:13                                        _propagateToListeners
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/future_impl.dart 557:7                                         [_complete]
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream_pipe.dart 61:11                                         _cancelAndValue
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/async/stream.dart 1530:7                                             <fn>
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 334:14  _checkAndCall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/_internal/js_dev_runtime/private/ddc_runtime/operations.dart 339:39  dcall
C:/b/s/w/ir/cache/builder/src/out/host_debug/dart-sdk/lib/html/dart2js/html_dart2js.dart 37309:58                              <fn>
)
  • allow cross origin in dart ` Future getApiData()async { final response = await http.get( 'http://myurl/product', headers: { "Accept": "application/json", "Access-Control_Allow_Origin": "*" }); print(response.statusCode); print(response.body); } ` as well as in django ` CORS_ORIGIN_ALLOW_ALL = False CORS_ORIGIN_WHITELIST = ( 'http://localhost:8000', ) ` – sk shahriar ahmed raka Aug 11 '22 at 18:54

1 Answers1

0

From your fetch_data.dart , fetch api with Control_Allow_Origin": "*"

Future getApiData()async { 
      final response = await http.get( 'myurl/product', 
            headers: { "Accept": "application/json", "Acces-Control_Allow_Origin": "*" });
       print(response.statusCode); 
       print(response.body); 
}

Then in your Django backend

1. Install django-cors-headers using PIP

pip install django-cors-headers

2. Add corsheaders to installed applications section in the settings.py file:

INSTALLED_APPS = [

   ...

   'corsheaders',

   ...

]

3. Add corsheaders.middleware.CorsMiddleware to middleware section in settings.py file:

MIDDLEWARE = [
  'django.middleware.security.SecurityMiddleware',
  ...
  'django.middleware.clickjacking.XFrameOptionsMiddleware',
  'corsheaders.middleware.CorsMiddleware',
]

4. If you want to allow access for all domains, set the following variable to TRUE in settings.py file:

CORS_ORIGIN_ALLOW_ALL = True

Alternatively, you can specify which domains you want to give access to by doing the following in settings.py file:

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
  'http://localhost:8000',
)