Ajax到Laravel返回404并且Responsejson未定义

时间:2013-10-16 05:21:05

标签: javascript php jquery ajax laravel-4

当$ $ .ajax从一个跨域请求执行下面的控制器的路由时,我得到一个空响应。当我取消注释var_dump行时,我得到一个带有数据的响应,否则我得到一个404响应,而responsejson对象是未定义的。任何帮助非常感谢。当我直接在浏览器中访问相同路径的get等效时,我得到一个有效的json响应。

<?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');
}
}

2 个答案:

答案 0 :(得分: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 :(得分:1)

事实证明我发送了两次标题。我最初遇到CORS问题,因为我从运行在本地主机上的Angular JS前端连接到也在本地主机上但在不同端口上运行的laravel API。我在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;
});

我希望这有助于某人。