Error "Content-Type is not allowed by Access-Control-Allow-Headers in preflight response"

2

I'm doing my api, in php, and I get the following warning

  

XMLHttpRequest can not load link . Request header field Content-Type is not allowed by Access-Control-Allow-Headers in preflight response.

Here is the beginning of my php code:

<?php
header("Access-Control-Allow-Origin: *");
ini_set('display_errors', true);
error_reporting(E_ALL);

include_once("conexao.php");

$pdo = conectar();

$data = file_get_contents("php://input");
$data = json_decode($data);

$eh_profissional = $data->is_professional;

Follow my controller:

angular.module('servi.controllers', ['ngCordova'])

.controller('cadastroCtrl', ['$scope', '$stateParams', '$http', 
$cordovaSQLite', '$window', '$state', function ($scope, $stateParams, $http, 
$cordovaSQLite, $window, $state) {

$scope.email = [];

$scope.cadastrar = function(usuario){

$http.post("http://vigilantescomunitarios.com/serviapp/api_gustavo/register.php", usuario).success(function(response){
        // http://vigilantescomunitarios.com/serviapp/api/register

        })
    }

}])

Does anyone know what the problem is? Thank you.

    
asked by anonymous 08.05.2017 / 21:25

2 answers

2

The error says that it was not allowed to use the header Content-Type in the request (for example when Ajax requests your PHP) and that it should be released using Access-Control-Allow-Headers

For Ajax the only headers you can adjust are:

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type , however the latter only allows values:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

  • In your case, $http.post (Angular.js) should be sending something like application/json , which is not one of the 3 allowed values.

Then in PHP you can adjust to:

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");
    
08.05.2017 / 21:40
0

If you do not have access to the server to add the headers:

You can use one of the extensions for chrome (for development) :

Allow-Control-Allow-Origin: *

CORS Toggle

These extensions disable chrome security with respect to communication from different hosts and without the authorization definition in the header (as done by the header () function).

Summarizing This error is corrected by adding: (PHP)

header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Headers: Content-Type");

Or your API consuming front-end must be on the same host (IP + port) as your API.

    
08.05.2017 / 22:20