1
votes

I have a module in Ionic who calls an api in PHP.

import { LoadingController } from 'ionic-angular';
import { Injectable } from '@angular/core';
import { Http, Headers } from '@angular/http';
import 'rxjs/add/operator/map';

....

 getPatrocinios(cidade) {
   var headers = new Headers();
   headers.append('idCidade', cidade);
   let url = 'http://somesite.com/test/index.php';
   return this.http
      .get(url, { headers: headers })
      .map(res => res.json());
  }

in PHP module i made this:

<?php
header('Access-Control-Allow-Origin: *');  
header('Access-Control-Allow-Credentials: true');
header('Access-Control-Allow-Methods: GET,HEAD,OPTIONS,POST,PUT');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');

define('CHARSET', 'UTF-8');
define('REPLACE_FLAGS', ENT_COMPAT | ENT_XHTML);

function getHeaders($header_name = null) {
  $keys=array_keys($_SERVER);   
  if(is_null($header_name)) {
      $headers=preg_grep("/^HTTP_(.*)/si", $keys);
  } else {
    $header_name_safe=str_replace("-", "_", strtoupper(preg_quote($header_name)));
    $headers=preg_grep("/^HTTP_${header_name_safe}$/si", $keys);
  }

  foreach($headers as $header) {
    if(is_null($header_name)) {
      $headervals[substr($header, 5)]=$_SERVER[$header];
    } else {
      return $_SERVER[$header];
    }
  }
  return $headervals;
}
$id_cidade = getHeaders("idCidade");

...

Using Postman and puting the 'idCidade' in Headers tab, it works fine (status=200), but in the emulator of ionic i have the error: Request header field idCidade is not allowed by Access-Control-Allow-Headers in preflight response.

I tried most solution in stackoverflow, but still not working.

Some extra information:

  • Ionic Framework: 3.9.2
  • Ionic App Scripts: 3.1.8
  • Angular Core: 5.2.9
  • Angular Compiler CLI: 5.2.9
  • Node: 8.11.1

Someone to help me?

2

2 Answers

2
votes

Request header field idCidade is not allowed by Access-Control-Allow-Headers in preflight response

What response header Access-Control-Allow-Headers Tells the browser is what request headers are allowed in the request. Look at the list that you provided

header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');

The idCidade header is not included in that list.

-1
votes

I had the same problem in an App when i run with Ionic Serve. If you are using Google Chrome, you can install a CORS extension, enable it, and testing again, in my case, that works.

Heres the extension i used: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi

If the problem already exist, we can check other ways