AngularJS POST失败:响应为preflight具有无效HTTP状态code 404状态、preflight、AngularJS、POST

2023-09-11 01:29:16 作者:厌温袭

我知道有很多这样的问题,但没有我见过有固定我的问题。我已经至少使用了3 microframeworks。他们都不行了,做一个简单的POST,它应该会返回数据返回:

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:

在angularJS客户端:

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() {
    $http({
      method: 'GET',
      url: baseUrl + '/get'
    }).then(function successCallback(response) {
      $scope.response = response.data.response;
    }, function errorCallback(response) { });
  };

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

在SlimPHP服务器:

The SlimPHP server:

<?php
    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();

        $app->response->setStatus(200);
        echo json_encode($array);
    }); 

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

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

    $app->run();

我已经启用CORS和GET请求的工作。在HTML的更新与服务器发送的JSON内容。不过,我收到了

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

XMLHtt prequest无法加载的http://本地主机:8080 / server.php /帖子。响应preflight具有无效HTTP状态code 404 的

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

每次我尝试使用POST。为什么呢?

Everytime I try to use POST. Why?

编辑:请求/资源所要求的尖

The req/res as requested by Pointy

推荐答案

好了,所以这里就是我想通了这一点。 这一切,是因为有CORS政策。 POST请求之前,Chrome浏览器在做这应该被处理,并承认之前,实际的请求与服务器的preflight OPTIONS请求。现在,这真的不是我想要这样一个简单的服务器。因此,重置头的客户端prevents的preflight:

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.post = {};
  $httpProvider.defaults.headers.put = {};
  $httpProvider.defaults.headers.patch = {};
});

浏览器现在将直接发送POST。希望这可以帮助很多人在那里......我真正的问题不明白CORS不够。

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

链接到一个很好的解释: http://www.html5rocks.com/en/tutorials / CORS /

Link to a great explanation: http://www.html5rocks.com/en/tutorials/cors/

荣誉给这个答案用于显示我的方式。

Kudos to this answer for showing me the way.