我的客户端应用程序是angularJS应用程序。服务器由Laravel 5构建。
在客户端,我执行jsonp CORS请求:
$http.jsonp("http://server.com/api?callback=JSON_CALLBACK")
在laravel服务器中,返回一个json数据:
return Response()->json($query);
然而,当我尝试时
$http.jsonp("http://server.com/api?callback=JSON_CALLBACK")
.then(function(response){
alert('success');
});
或
$http.jsonp("http://server.com/api?callback=JSON_CALLBACK")
.success(function(response){
alert('success');
});
两种状态均为200 OK
。但不会出现任何警报。我尝试
$http.jsonp("http://server.com/api?callback=JSON_CALLBACK")
.then(function(response){
alert('success');
},function(error){
alert('fail');
});
结果为200 OK
状态,但警报为"失败"!我该如何解决这个问题?谢谢
JSONP需要服务器端的回调函数"JSON_callback"。或者,您可以使用代理。http://www.whateverorigin.org/
$http.jsonp
将请求查询字符串参数从callback=JSON_CALLBACK
转换为callback=angular.callbacks._0
。
在Laravel中的控制器中,您需要将前缀添加到响应字符串中。
return $request->input('callback')."(".$query.")";
然后,角度应用程序将确认该响应并传递给.then
或.success
功能。