CORS with Dart, how do I get it to work?


Just started tinkering with Dart and I decided to write a simple Http Server and a client. My server code:


final HOST = "";
final PORT = 8080;
final LOG_REQUESTS = true;

void main() {
  HttpServer server = new HttpServer();
  server.addRequestHandler((HttpRequest request) => true, requestReceivedHandler);
  server.listen(HOST, PORT);
  print("Server is running on ${PORT}."); 

void requestReceivedHandler(HttpRequest request, HttpResponse response) {
  var pathname = request.uri;
  var apiresponse="";
    print("Request: ${request.method} ${pathname}");
  if(pathname == '/api'){
    response.headers.set(HttpHeaders.CONTENT_TYPE, "text/plain; charset=UTF-8");
    response.headers.add("Access-Control-Allow-Methods", "POST, OPTIONS, GET");
    response.headers.add("Access-Control-Allow-Origin", "*");
    response.headers.add('Access-Control-Allow-Headers', '*');
    print('welcome to the good life');
    response.outputStream.writeString("API Call");

My client code:


class dartjson {

  dartjson() {

  void run() {
    write("Hello World!");

  void fetchFeed(){
    XMLHttpRequest xhr = new XMLHttpRequest();
    var url = "";"GET", url, true);
    xhr.setRequestHeader('Content-Type', 'text/plain');
    //xhr.setRequestHeader('Access-Control-Request-Headers', '');
    document.query('#status').innerHTML = xhr.responseText;


void main() {
  new dartjson().fetchFeed();

I keep getting the error:

XMLHttpRequest cannot load Origin is not allowed by Access-Control-Allow-Origin.

What I’m I doing wrong?


you could simplify your life and run both server/client scripts from the same host:port address. There is a small webserver example at that serves static files too. Add your ‘/api’ handler and make sure your client files are in the same directory. The example server is a lot slower than the Dart Editor builtin server that runs on port 3030.

Answered By – Michael Haubenwallner

Answer Checked By – David Marino (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *