IM向Laravel网络服务提出简单请求。
这是控制器中的响应:
data = array(
'name' => 'Dummy',
'size' => 'XL',
'color' => 'Blue'
);
return Response::json($data);
使用POSTman我可以看到一切看起来很好: 网址:
Response:
{"name":"Dummy","size":"XL","color":"Blue"}
HEADERS:
Cache-Control →no-cache
Connection →Keep-Alive
Content-Type →application/json
Date →Mon, 04 Nov 2013 15:15:27 GMT
Keep-Alive →timeout=5, max=100
Server →Apache/2.4.6 (Ubuntu) PHP/5.5.3-1ubuntu2
Transfer-Encoding →chunked
X-Powered-By →PHP/5.5.3-1ubuntu2
然后我进入一个简单的javascript调用,如:
$.getJSON("http://localhost/myapi/public/content", function(json) {
console.log("log " + json.name);
});
或
$.ajax({
type: 'get',
url: 'http://localhost/myapi/public/content',
dataType: 'json',
async: false,
success: function(data) { alert("success"); },
error: function() { alert("error"); } });
Firefox控制台返回“200 OK”,但Javascript始终报告错误。
问题在哪里?
解决方案:
Laravel Response默认情况下不发送
header('Access-Control-Allow-Origin: *');
刚刚添加,现在我正确地获取了json数据。
答案 0 :(得分:1)
另一种解决方案是在app / filters.php中添加App::after
中间件
App::after(function($request, $response)
{
$response->headers->set('Access-Control-Allow-Origin', '*');
// You may also require these additional method calls
$response->headers->set('Access-Control-Allow-Methods', 'POST, GET, PUT, DELETE, OPTIONS');
$response->headers->set('Access-Control-Max-Age', '1000');
$response->headers->set('Access-Control-Allow-Headers', 'X-Requested-With, Origin, X-Csrftoken, Content-Type, Accept');
return $response;
});