如何能够jQuery $ .get,$ .post并获得所需的结果但是角度可以&$ 39; $ 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);
});
我在这里做错了什么?
答案 0 :(得分:2)
.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);
}
});
可能在飞行前请求失败