Dee*_*riz 58 javascript php ajax cors angularjs
我知道有很多这样的问题,但我见过的都没有解决我的问题.我已经使用过至少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');
});
}
});
Run Code Online (Sandbox Code Playgroud)
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();
Run Code Online (Sandbox Code Playgroud)
我已经启用了CORS,并且GET请求正常工作.html使用服务器发送的JSON内容进行更新.但是我得到了一个
XMLHttpRequest无法加载http:// localhost:8080/server.php/post.预检的响应具有无效的HTTP状态代码404
每次我尝试使用POST.为什么?
Dee*_*riz 84
好的,这就是我怎么想出来的.这一切都与CORS政策有关.在POST请求之前,Chrome正在执行预检OPTIONS请求,该请求应在实际请求之前由服务器处理和确认.现在这真的不是我想要的这么简单的服务器.因此,重置标头客户端可防止预检:
app.config(function ($httpProvider) {
$httpProvider.defaults.headers.common = {};
$httpProvider.defaults.headers.post = {};
$httpProvider.defaults.headers.put = {};
$httpProvider.defaults.headers.patch = {};
});
Run Code Online (Sandbox Code Playgroud)
浏览器现在将直接发送POST.希望这可以帮助很多人...我真正的问题是不够理解CORS.
链接到一个很好的解释:http://www.html5rocks.com/en/tutorials/cors/
感谢这个答案给我指路.
您已启用CORS并Access-Control-Allow-Origin : *在服务器中启用.如果您仍然使用GET方法并且POST方法不起作用那么可能是因为问题Content-Type和data问题.
第一个AngularJS传输的数据Content-Type: application/json不是由某些Web服务器(特别是PHP)本机序列化的.对于他们,我们必须将数据传输为Content-Type: x-www-form-urlencoded
示例: -
$scope.formLoginPost = function () {
$http({
url: url,
method: "POST",
data: $.param({ 'username': $scope.username, 'Password': $scope.Password }),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' }
}).then(function (response) {
// success
console.log('success');
console.log("then : " + JSON.stringify(response));
}, function (response) { // optional
// failed
console.log('failed');
console.log(JSON.stringify(response));
});
};
Run Code Online (Sandbox Code Playgroud)
注意:我$.params用于序列化要使用的数据Content-Type: x-www-form-urlencoded.或者,您可以使用以下javascript函数
function params(obj){
var str = "";
for (var key in obj) {
if (str != "") {
str += "&";
}
str += key + "=" + encodeURIComponent(obj[key]);
}
return str;
}
Run Code Online (Sandbox Code Playgroud)
并且用于params({ 'username': $scope.username, 'Password': $scope.Password })序列化它,因为Content-Type: x-www-form-urlencoded请求只获取username=john&Password=12345表单中的POST数据.
| 归档时间: |
|
| 查看次数: |
169983 次 |
| 最近记录: |