AlexOlival AlexOlival - 1 year ago 215
Javascript Question

AngularJS POST Fails: Response for preflight has invalid HTTP status code 404

I know there are a lot of questions like this, but none I've seen have fixed my issue. I've used at least 3 microframeworks already. All of them fail at doing a simple POST, which should return the data back:

The angularJS client:

var app = angular.module('client', []);

app.config(function ($httpProvider) {
//uncommenting the following line makes GET requests fail as well
//$httpProvider.defaults.headers.common['Access-Control-Allow-Headers'] = '*';
delete $httpProvider.defaults.headers.common['X-Requested-With'];

app.controller('MainCtrl', function($scope, $http) {
var baseUrl = 'http://localhost:8080/server.php'

$scope.response = 'Response goes here';

$scope.sendRequest = function() {
method: 'GET',
url: baseUrl + '/get'
}).then(function successCallback(response) {
$scope.response =;
}, function errorCallback(response) { });

$scope.sendPost = function() {
$ + '/post', {post: 'data from client', withCredentials: true })
.success(function(data, status, headers, config) {
.error(function(data, status, headers, config) {

The SlimPHP server:

require 'vendor/autoload.php';

$app = new \Slim\Slim();
$app->response()->headers->set('Access-Control-Allow-Headers', 'Content-Type');
$app->response()->headers->set('Content-Type', 'application/json');
$app->response()->headers->set('Access-Control-Allow-Methods', 'GET, POST, OPTIONS');
$app->response()->headers->set('Access-Control-Allow-Origin', '*');

$array = ["response" => "Hello World!"];

$app->get('/get', function() use($array) {
$app = \Slim\Slim::getInstance();

echo json_encode($array);

$app->post('/post', function() {
$app = \Slim\Slim::getInstance();

$allPostVars = $app->request->post();
$dataFromClient = $allPostVars['post'];
echo json_encode($dataFromClient);


I have enabled CORS, and GET requests work. The html updates with the JSON content sent by the server. However I get a

XMLHttpRequest cannot load http://localhost:8080/server.php/post. Response for preflight has invalid HTTP status code 404

Everytime I try to use POST. Why?

EDIT: The req/res as requested by Pointy
req/res headers

Answer Source

Ok so here's how I figured this out. It all has to do with CORS policy. Before the POST request, Chrome was doing a preflight OPTIONS request, which should be handled and acknowledged by the server prior to the actual request. Now this is really not what I wanted for such a simple server. Hence, resetting the headers client side prevents the preflight:

app.config(function ($httpProvider) {
  $httpProvider.defaults.headers.common = {};
  $ = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};

The browser will now send a POST directly. Hope this helps a lot of folks out there... My real problem was not understanding CORS enough.

Link to a great explanation:

Kudos to this answer for showing me the way.