3

I'm building an application and was using the below test code to test out angular http.Post()

But I am receiving a strange error that my preflight is not succeeding.

The client code is below

<!DOCTYPE html>
<html>
<script src= "http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<body>

<div ng-app="myApp" ng-controller="customersCtrl"> 

<ul>
    {{ names }}
</ul>

</div>

<script>
var app = angular.module('myApp', []);


app.controller('customersCtrl', function($scope, $http) {
  $http.post("http://ec2-52-3-54-45.compute-1.amazonaws.com/api/user/dogs",{id:'hello word!'})
  .success(function (response) {
    $scope.names = response});
});
</script>

</body>
</html>

The .htaccess file on the other end is below

  Header set Access-Control-Allow-Methods "POST"
  Header set Access-Control-Allow-Origin "*"
RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]

And the PHP which should be handling this is

<?php
header('Access-Control-Allow-Headers: Origin, X-Requested-With, Content-Type, Accept');
header( ‘Access-Control-Allow-Headers: Authorization, Content-Type’ );
header("Access-Control-Allow-Origin: *");

I'm not sure why I am getting this error or what exactly I am doing wrong. Any help or insight is very much appreciated.

WeeniehuahuaXD
  • 852
  • 3
  • 10
  • 30

1 Answers1

3

This htaccess code should work:

Header always set Access-Control-Allow-Origin "*"
Header always set Access-Control-Allow-Headers "Origin, X-Requested-With, Content-Type, Access-Control-Allow-Origin"
Header always set Access-Control-Allow-Methods "PUT, GET, POST, DELETE, OPTIONS"

Angularjs before make a POST request it make an OPTIONS request

Carlos Mayo
  • 2,054
  • 1
  • 19
  • 35
  • seems to have created a new error "'Access-Control-Allow-Origin' does not match '*, *')." – WeeniehuahuaXD Sep 04 '15 at 21:53
  • I usually don't set the headers in the .htaccess, in php code I make: `header('Access-Control-Allow-Origin: *'); header('Access-Control-Allow-Methods: POST, GET, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: X-Requested-With, content-type, X-Token, x-token');` – Carlos Mayo Sep 04 '15 at 22:02
  • Also [here](http://stackoverflow.com/a/9866124/151689) you have a function for custom CORS request – Carlos Mayo Sep 04 '15 at 22:05
  • Thank you! For whatever strange reason, the PHP did the trick! – WeeniehuahuaXD Sep 04 '15 at 22:05