2013-10-16 118 views
1

當我從一個跨域請求執行下面的控制器的路由I $ .ajax時,我得到一個空的響應。當我取消var_dump行的註釋時,我得到一個帶有數據的響應,否則我得到一個404響應,而responsejson對象是未定義的。任何幫助不勝感激。當我直接在瀏覽器中訪問相同路由的get等價物時,我得到一個有效的json響應。Ajax Laravel返回404和Responsejson未定義

<?php 

use App\Models\User; 

class AuthenticationController extends \BaseController { 

public function getLogin() { 
    return $this->postLogin(); 
} 

public function postLogin() { 
    $credentials = array(
     'email' => Input::get('email'), 
     'password' => Input::get('password') 
    ); 

    try { 
     $user = Sentry::authenticate($credentials, false); 

     if ($user) { 
      //var_dump(array('flash' => 'Authentication failed')); 
      //return Response::json(array('flash' => 'Authentication failed'), 401); 
      return $user->toJson(); 
     } 
    } catch (Exception $e) { 
     return Response::json(array('flash' => 'Authentication failed'), 401); 
    } 
} 

public function getLogout() { 
    Sentry::logout(); 
    return Response::json(array('flash' => 'Logged out'), 200); 
    //return Redirect::route('admin.login'); 
} 
} 

回答

1

事實證明,我會發送標題兩次。由於我從在本地主機上運行的Angular JS前端連接到此本地主機上運行的laravel API,但在另一個端口上運行,我最初遇到了CORS問題。我在我的routes.php文件中像這樣的頂部發送標題:

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

文件,即使我的filters.php已有的代碼如下所示:

App::before(function($request) 
{ 
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') { 

    header('Access-Control-Allow-Origin', '*'); 
    header('Access-Control-Allow-Methods', 'GET, POST, OPTIONS'); 
    header('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Request-With'); 
    header('Access-Control-Allow-Credentials', 'true'); 

    exit; 
} 
}); 

App::after(function($request, $response) 
{ 
$response->headers->set('Access-Control-Allow-Origin', '*'); 
$response->headers->set('Allow', 'GET, POST, OPTIONS'); 
$response->headers->set('Access-Control-Allow-Headers', 'Origin, Content-Type, Accept, Authorization, X-Requested-With'); 
$response->headers->set('Access-Control-Allow-Credentials', 'true'); 
return $response; 
}); 

我希望這可以幫助別人。

1

你有沒有嘗試過這樣的事情:

try { 
    $user = Sentry::authenticate($credentials, false); 

    if ($user) { 
     return Response::json($user); 
     # or 
     Response::json($user)->send(); 
    } 
} catch (Exception $e) { 
    return Response::json(array('flash' => 'Authentication failed'), 401); 
} 
+1

SeanNieuwoudt,我相信你的代碼會工作。感謝您及時的回覆。我發現問題來自我發送頭兩次。 – DamongoCoder