Client in DART comunicate with server in PHP: acce

2019-08-01 06:56发布

问题:

This is my client:

  import 'dart:html';
  void main() {
    var request = new HttpRequest();
    request.open('post','http://127.0.0.1/dartphp/index.php',async: true);
    request.send("some data");
  }

and my server:

  <?php  header("Access-Control-Allow-Origin: http://127.0.0.1:3030");                
         header("Access-Control-Allow-Methods: POST, GET, OPTIONS");
  ?>
  <html><body>
  <?php 
  echo "postback";
  echo "<pre><br>post<br>";
  echo $HTTP_RAW_POST_DATA;
  echo "</pre><br>";
  ?>               
  </body></html>

I execute the dart in Dartium on 3030 and have Apache listening on 80. The error I get is: XMLHttpRequest cannot load http://127.0.0.1/dartphp/index.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://127.0.0.1:3030' is therefore not allowed access.

I read the articles Send data between php and dart and CORS with Dart, how do I get it to work? but in the meantime syntax has changed or the solution is not applicable to my problem,

  • for the first 'on.readyStateChange.add' no longer exists

  • for the second 'request.response.headers.add' is not possible, as 'response' has no 'headers' defined

What has to be changed, so that can 'request.onReadyStateChange.listen((_)' to the response

回答1:

The server needs to add the Access-Control-Allow-Origin header not the client.

Your page is initally load from http://127.0.0.1:3030 and then wants to access http://127.0.0.1/dartphp/index.php which is considered a different domain.

The client sends a request to the server to check if it responds with a Access-Control-Allow-Origin header that fits the clients origin (which * as wildcard does) after this the actual request is sent.

Try setting the following headers

"Access-Control-Allow-Origin", "http://127.0.0.1:3030"
"Access-Control-Allow-Methods", "POST, GET, OPTIONS"