1

IM 对 Laravel Web 服务进行简单的请求。

这是控制器中的响应:

data = array(
 'name' => 'Dummy',
 'size' => 'XL',
 'color' => 'Blue'
 );
 return Response::json($data);

使用 POSTman 我可以看到一切正常: URL:

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 响应默认不发送

header('Access-Control-Allow-Origin: *');

刚刚添加,现在我正确获取了 json 数据。

4

1 回答 1

1

App::after另一种解决方案是在 app/filters.php 中添加一个中间件

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;
});
于 2013-11-05T09:23:43.520 回答