1
votes

I have the next message related with CORS when I send a username and password from APP in IONIC 3:

Blockquote Access to XMLHttpRequest at 'http://localhost/Service_mobile/service.php' from origin 'http://localhost:8100' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I have the next headers in service.php:

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Headers: *');
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
header('Content-Type: application/json; charset=utf-8');

require_once($_SERVER['DOCUMENT_ROOT'] . '/libs/adodb5/adodb.inc.php');

function conect()
{
    global $database, $server, $db_user, $db_password;

    $database = "test";
    $server = "localhost";
    $db_user = "sa";
    $db_password = "sa";

    $db = ADONewConnection('odbc_mssql');
    $dsn = "Driver={SQL Server};Server=" . $server . ";Database=" . $database . ";";
    $db->Connect($dsn, $db_user, $db_password);
    return $db;
}

$postjson = json_decode(file_get_contents('php://input'),true);

if($postjson["action"] == "verify"){
    echo 'TEST';
}

And the next code in conection.ts

import { Injectable } from '@angular/core';
import { Http, Headers, RequestMethod ,RequestOptions } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class ConexionAPI{
    constructor(private http:Http){

    }
login(username,password){
    var _url = "http://localhost/Service_mobile/service.php";
    var _body = {"action":"verify","ID_USER": username, "PASSWORD": password };
    var _header = new Headers({'Content-Type':'Application/json'});
    var _option = new RequestOptions({method:RequestMethod.Post,headers:_header});
    return this.http.post(_url,_body,_option).map(res=>res.json());
}
}

home.ts

import { Component } from '@angular/core';
import { NavController} from 'ionic-angular';
import { ToastController } from 'ionic-angular';
import { Conex } from '../conection/conection';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [Conex]
})
export class HomePage {
  username: string;
  password: string;

  constructor(public navCtrl: NavController,
              public conex: Conex,
              public toastCtrl: ToastController) {

  }

  enter(){
    this.conexion.login(this.username,this.password).subscribe(data=>{
      if(data==null){
        let toast = this.toastCtrl.create({
          message: 'Error!',
          duration: 3000
        });
        toast.present();
      }else{
        let toast = this.toastCtrl.create({
          message: 'Correct!',
          duration: 3000
        });
        toast.present();
      }
    });
  }
}

I forgot something ??

2
Your PHP script will need to respond with those headers to an OPTIONS request. Where in your code are you setting the headers?Phil
I don't have them. Can you give me a help with that ??Pabloco
What do you mean? I'm talking about the ones in your question abovePhil
The error message says "No 'Access-Control-Allow-Origin' header is present", so clearly header('Access-Control-Allow-Origin: *'); isn't being run. There isn't enough code in the question to determine why that is the case.Quentin
I updated the postPabloco

2 Answers

0
votes

Add in your PHP file. This is working for me.

header('Access-Control-Allow-Origin: *');
header("Access-Control-Allow-Headers: X-API-KEY, Origin, X-Requested-With, Content-Type, Accept, Access-Control-Request-Method, Authorization");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
   $method = $_SERVER['REQUEST_METHOD'];
   if ($method == "OPTIONS") {
       die();
   }
0
votes

The problem can be solved on the app's end, without changing the backend settings (which is, in fact, not a secure solution)

If you are having problems when the app is ran with live-reload (e.g. on device with -l param or in the browser) - the ionic proxy can help:

“proxies”: [
  {
   “path”: “/api”,
   “proxyUrl”: “http://your-backend-domain.com”
  }
]

If the problem happens in the production build, you are in a bigger trouble. The problem happens because of WKWebView, introduced in the Ionic 3, which is a faster/better/safer web renderer -- and which has very strict CORS-related restrictions.

There are ways to resolve it, though:

good luck! CORS is a big/bad issue when it comes to Ionic :)