How to communicate with a local API with AngularDart

498 views Asked by At

I can communicate in AngularDart with a public API but not with my local API.

 String _url = 'localhost:8000/kanji_detail/1000/?format=json';
 String _url = "http://jsonplaceholder.typicode.com/posts/1";

I can get the JSON info from both urls in my browser, but can only connect in AngularDart with the second url. I tried the http methods and client instead of the BrowserClient with no effect, and the code only works when using the BrowserClient and a public API.

Here is the code:

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

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


@Component (
  selector: "test",
  template: """
    <button (click)="change_info()">{{info}}</button>
    """,
)
class Test {
  BrowserClient client = new BrowserClient();
  //var client = new http.Client();
  String info = "default info";
  String _url = 'http://127.0.0.1:8000/kanji_detail/1000/?format=json';
  //String _url = "http://jsonplaceholder.typicode.com/posts/1";

  Future get_info() async {
    var response = await client.get(_url);
    info = JSON.decode(response.body);
    //return JSON.decode(response.body);
  }

  change_info() {
    get_info();
  }

}
1

There are 1 answers

0
Pedro Garcia On

The problem wasn't about Angular Dart but it was on the server configuration, Django in my case. I solved it by enabling CORS headers configuration and whitelisting there my localhost. In Django I:

  1. Installed django-cors-header module in the terminal.

    pip install django-cors-headers

  2. Added the module to the installed apps list.

    INSTALLED_APPS = ( ... 'corsheaders', ... )

  3. Added the middleware class to the configuration

    MIDDLEWARE_CLASSES = ( ... 'corsheaders.middleware.CorsMiddleware', ... )

  4. And whitelisting localhost.

    CORS_ORIGIN_WHITELIST = ( 'localhost:8080', '127.0.0.1:8080' )