2

当我 $.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');
}
}
4

2 回答 2

2

你有没有尝试过这样的事情:

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);
}
于 2013-10-16T05:55:33.707 回答
2

事实证明我发送了两次标题。我最初在使用 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;
});

我希望这可以帮助别人。

于 2013-10-16T15:34:32.393 回答