小编典典

AngularJS POST失败:飞行前响应具有无效的HTTP状态代码404

ajax

我知道有很多这样的问题,但是我所见的问题都没有解决。我已经使用了至少3个微框架。所有这些都无法执行简单的POST,它应该将数据返回:

angularJS客户端:

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服务器:

<?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内容进行更新。但是我得到了

XMLHttpRequest无法加载 http:// localhost:8080 / server.php /
post
。飞行前的响应具有无效的HTTP状态代码404

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

编辑:根据Pointy的要求 req /
res标头


阅读 362

收藏
2020-07-26

共1个答案

小编典典

好的,这就是我的解决方法。这都与CORS政策有关。在发布POST请求之前,Chrome正在执行预检OPTIONS请求,服务器应在实际请求之前对其进行处理和确认。现在,这真的不是我想要的那样简单的服务器。因此,重置标头客户端可以防止预检:

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

浏览器现在将直接发送POST。希望这对很多人有帮助…我的真正问题是对CORS的了解不足。

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

2020-07-26