redstone-dart / redstone

A metadata driven microframework for Dart.
http://redstone-dart.github.io/redstone
MIT License
342 stars 42 forks source link

'XMLHttpRequest cannot load' error on HTTP Requests from Dart client to local Redstone server #55

Closed cgarciae closed 9 years ago

cgarciae commented 9 years ago

I've lately been trying to build a Dart client that communicates with my Redstone server. If I run this url (localhost:8080/id/6192449487634432) on any browser I get back a JSON that I've set up, however, if a use

HttpRequest
    .getString ("http://localhost:8080/id/6192449487634432")
    .then (print);

on the Dart client, I get this weird error

XMLHttpRequest cannot load http://localhost:8080/id/6192449487634432. No 'Access-Control-Allow-Origin' 
header is present on the requested resource. Origin 'http://localhost:8081' is therefore not allowed access.

Is this a client or server issue? I've been told to modify the HttpResponse headers but since Redstone handles everything I don't know where to start.

Thanks a lot!

luizmineo commented 9 years ago

This is a CORS issue, you can learn more about it here;

Just add this interceptor to your server to enable CORS requests. Note that it enables requests coming from any origin, so maybe you'll want to customize it:

@app.Interceptor(r'/.*')
handleResponseHeader() {
  if (app.request.method == "OPTIONS") {
    //overwrite the current response and interrupt the chain.
    app.response = new shelf.Response.ok(null, headers: _createCorsHeader());
    app.chain.interrupt();
  } else {
    //process the chain and wrap the response
    app.chain.next(() => app.response.change(headers: _createCorsHeader()));
  }
}

_createCorsHeader() => {"Access-Control-Allow-Origin": "*"};
cgarciae commented 9 years ago

Thanks a lot! This is really helpful. For the moment I avoid CORS by trying to serve the files myself instead of relying on "Run in Dartium" which creates a separate server, but now the problem of serving the files has come up.

I'll write another issue. Sorry for bothering you so much!