怎么可以jQuery $.get,$.post并得到想要的结果但角度不能$http.get,$http.post?为什么原始政策不适用于角度而非
jquery?
Laravel后端,有棱角的前端.我正在考虑使用jQuery,因为它不会阻止CRUD操作在客户端发生.
我配置了$http和$httpProvider ……
.run(function($http){
$http.defaults.headers.common['Access-Control-Allow-Origin'] = "*";
$http.defaults.headers.common['Access-Control-Allow-Methods'] = "GET, POST, PUT, DELETE, OPTIONS";
$http.defaults.headers.common['Access-Control-Allow-Headers'] = "Authorization";
})
.config(function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
})
laravel正在发回相应的标题……
App::after(function($request, $response)
{
// header('Access-Control-Allow-Origin', '*');
$response->headers->set('Access-Control-Allow-Origin', '*');
});
所以奇怪的是角度$http无法从服务器返回任何内容并产生此错误:
XMLHttpRequest cannot load http://0.0.0.0:8000/api/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.
但是jQuery $.get和$.post正常工作!
$.post('http://0.0.0.0:8000/api/test', function(resp){
console.log(resp);
});
我在这做错了什么?
最佳答案
.config(['$httpProvider', function($httpProvider) {
$httpProvider.defaults.useXDomain = true;
delete $httpProvider.defaults.headers.common['X-Requested-With'];
}
]);
仅将useXDomain设置为true是不够的. AJAX请求也与X-Requested-With标头一起发送,表明它们是AJAX.删除标头是必要的,因此服务器不会拒绝传入的请求.
尝试在filters.php中添加:
App::before(function($request)
{
if (Request::getMethod() == "OPTIONS") {
$headers = array(
'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
'Access-Control-Allow-Headers'=> 'X-Requested-With, content-type, Authorization',);
return Response::make('', 200, $headers);
}
});
它可能在飞行前请求失败