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 Response はデフォルトでは送信されません

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

追加したばかりで、jsonデータを正しく取得しています。

4

1 に答える 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 に答える