3

I'm trying to do a simple POST from angularjs to a dummy php file to understand how this works. Here in my angularjs part:

<html ng-app="loginApp">
  <head>
    <meta charset="utf-8">
    <title>Login</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css">
      <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.2.26/angular.min.js"></script>
    <script>
      var logindata = {username:'abc', password:'abc'}
      var loginApp = angular.module('loginApp', []);
      loginApp.controller('loginCtrl', function ($scope, $http){        
        var request = $http({
            method: "POST",
            url: "http://different-ip/a.php",                    
            data: logindata,
            headers: { 'Content-Type': 'multipart/form-data', 'Authorization': 'Basic ' + btoa(logindata.username + logindata.password), 
            'Access-Control-Allow-Origin': "*"}
        });

        request.success(
            function( data ) {
                $scope.someVariableName = data;
            }
        );
    });
    </script>
  </head>
  <body ng-controller="loginCtrl">
    <h2>Angular.js JSON Fetching Example</h2>
    <p> {{ someVariableName }} </p>
  </body>
</html>

Here is my PHP part (a.php) that resides on http://different-ip

<?php
  header("Access-Control-Request-Method: *");
  header("Access-Control-Request-Headers: *");
  header("Access-Control-Allow-Origin: *");
  file_put_contents("aa.txt", json_decode(file_get_contents('php://input'),true));
  file_put_contents("aaa.txt", getallheaders());
?> 

When I execute my angularjs file, the chrome console gives me this error:

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

When I try doing a post to this a.php using Postman, everything works fine. So why is angularjs not allowing it? I've tried to read about CORS and there is no straightforward answer to how this issue can be resolved (code wise). Can someone please help me out? Thanks in advance.

Prarthana Hegde
  • 361
  • 2
  • 7
  • 18
  • Try to check this 2 links regarding angularjs+CORS: http://stackoverflow.com/questions/21455045/angularjs-http-cors-and-http-authentication and http://stackoverflow.com/questions/27654135/angularjs-php-restful-cors-issue – Armen Feb 02 '16 at 11:20

2 Answers2

8

Added this instead of current headers to my PHP file and now it works! Thanks @Armen for your help!

    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);
    }
Prarthana Hegde
  • 361
  • 2
  • 7
  • 18
2

Add this 3 headers at top of a.php instead current ones with if condition

<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, DELETE, OPTIONS");
header("Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept, Authorization");

if($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
   header( "HTTP/1.1 200 OK" );
   exit;
}

file_put_contents("aa.txt", json_decode(file_get_contents('php://input'),true));
file_put_contents("aaa.txt", getallheaders());
?> 

You can check more about CORS here: http://www.w3.org/TR/cors/#access-control-allow-headers-response-header

Postman works because it is additional browser extension which don't cares about headers policy and don't check it before request.

Armen
  • 4,064
  • 2
  • 23
  • 40
  • I tried this. It is still giving me the same error! :( – Prarthana Hegde Feb 02 '16 at 07:42
  • @user3193036 i updated my answer with new 3 headers, can you retry ? – Armen Feb 02 '16 at 07:45
  • Now I'm getting this : Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource – Prarthana Hegde Feb 02 '16 at 07:54
  • @user3193036 i again updated my answer this should finally help you, can you retry ? – Armen Feb 02 '16 at 08:10
  • @user3193036 hmm seems there is some specific issue related to your browser + server which from here i can't understand, can you include in your question screenshots from browser network tab for `request` and `response` cases ? – Armen Feb 02 '16 at 11:23
  • I'm using chrome 48 and just my local server on XAMPP. There are specific headers to be included.. I don't know which ones though.. I've tried all possible combinations.. – Prarthana Hegde Feb 03 '16 at 10:27
  • I mean if your request goes with POST or OPTIONS ? as show in this image: https://www.google.com/imgres?imgurl=http://kevhuang.com/content/images/2015/04/options-request-network-panel.png&imgrefurl=http://kevhuang.com/lets-consider-the-options/&h=158&w=685&tbnid=_889ztoVkqCLtM:&docid=YTlztMM-mQ9JvM&ei=wdaxVuzsC4OvsAHKrYeABQ&tbm=isch&client=ubuntu&ved=0ahUKEwis0ZXZsdvKAhWDFywKHcrWAVAQMwg9KBgwGA&biw=1920&bih=933, can you attach same screenshoot of your network tab ? of course with hidden personal info – Armen Feb 03 '16 at 10:31