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 ??
OPTIONS
request. Where in your code are you setting the headers? – Philheader('Access-Control-Allow-Origin: *');
isn't being run. There isn't enough code in the question to determine why that is the case. – Quentin