Ionic 2 http request error

Asked

Viewed 169 times

0

I need to request a webserver in Ionic 2 and I have the following code :

constructor(private navController: NavController, public http: Http) {
      var url = 'http://localhost/APIPortManager/teste.php';
      var response = this.http.get(url)
      response.toPromise().then(response => {
         
          let dados = response.json()
          alert (dados)
      }).catch(err => {
      //let erro = err.json();
          alert ("erro")
      });
        //return response;
      //alert(response.toPromise()); // return object object
  }

However only returns me the error, how do I display the text ? Thank you Ps: I know the correct is not in the controller, I just need to display the code that pg has, I don’t even need the json if pg display hi I want to give Alert on hi just that. Update, error in console :

Xmlhttprequest cannot load http://localhost/. In the 'Access-Control-Allow-Origin' header is present on the requested Resource. Origin 'http://localhost:8100' is therefore not allowed access.

1 answer

0


In the.php test, you need to add some HEADERS to the answer (also known as CORS).

There’s an example here: ionic2 - photo upload via server

if (isset($_SERVER['HTTP_ORIGIN'])) {
    header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
    header('Access-Control-Allow-Credentials: true');
    header('Access-Control-Max-Age: 86400');    // cache for 1 day
}

// Access-Control headers are received during OPTIONS requests
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
    header("Access-Control-Allow-Methods: GET, POST, OPTIONS");

    if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
    header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");

    exit(0);
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.