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.

1

2 Answers 2

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);
    }
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @Armen.. I dug deeper with your help! :)
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.

7 Comments

I tried this. It is still giving me the same error! :(
@user3193036 i updated my answer with new 3 headers, can you retry ?
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
@user3193036 i again updated my answer this should finally help you, can you retry ?
@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 ?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.