【发布时间】:2016-02-13 03:27:19
【问题描述】:
我知道有很多这样的问题,但我所见过的都没有解决我的问题。我已经使用了至少 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。为什么?
【问题讨论】:
-
那么预检 HTTP 请求/响应是什么样的?
-
嗯,“OPTIONS”请求不需要明确的路由吗?您只有“GET”和“POST”的路由。
-
显然,当我尝试执行 POST 时,它会强制执行 OPTIONS 请求。它不应该与 POS T 一起使用吗?我有义务处理 OPTIONS 吗?为什么?
-
当 POST 请求具有某些特征时,浏览器会首先执行“预检”OPTIONS 事务。 POST 必须“简单”以避免它 - 这意味着它必须使用
application/x-www-form-urlencoded、multipart/form-data或text/plain的Content-Type,并且它不能有任何自定义标题。我不确定您的 POST 究竟是什么触发了预检测试。 -
可能是因为我正在发送一个 JSON 对象。感谢您的输入,一旦我回到代码中,我会尝试实现它
标签: javascript php angularjs ajax cors