Angular用于前端和Laravel用于Backend时的CORS头错误

时间:2017-02-03 06:44:54

标签: angularjs laravel cors

我正在使用角度js 1.5和laravel 5.4。

我已经在laravel中为CORS创建了中间件。它看起来如下:

public function handle($request, Closure $next)
{
    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');

    if (!$request->isMethod('options')) {
        return $next($request);
    }
}

现在,在Angular js中我创建了获取Bearer令牌的post请求,因此它完美无缺。我得到了令牌作为回应。然后我将它存储到会话中并使用拦截器在标头中为所有请求设置标记。

我的控制器如下:

app.controller('LoginController',function($scope,$http,$window,$state) {
$scope.vm.login = function() {

    $http({
            method: 'POST',
            url: apiUrl+'auth/token',
            data: $.param($scope.vm.logDetails),
            headers: {'Content-Type': 'application/x-www-form-urlencoded'}
        }).then(function(response) {
            if(response.data.access_token) {
                $window.sessionStorage.setItem('userInfo-token', response.data.access_token);
                $state.go('dashboard.masters_userroles');                   
            }               
        });
     }
});

我的工厂如下所示:

.factory('tokenInjector',function($window){
return {
    //For each request the interceptor will set the bearer token header.
    request: function($config) {

        if($window.sessionStorage.getItem('userInfo-token'))
        {
            var token=$window.sessionStorage.getItem('userInfo-token');
            console.log(token);
            //set authorization header
            $config.headers['Accept'] = 'application/json'
            $config.headers['Authorization'] = 'Bearer '+token;

        }
        return $config;
    }
}
})
.config(function ($httpProvider) {
     $httpProvider.interceptors.push('tokenInjector');
})

当它调用$state.go('dashboard.masters_userroles');此状态时,它会出现类似

的错误

MLHttpRequest cannot load http://api.local.support.com/api/masters/userroles?page=1. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://local.support.com' is therefore not allowed access.

1 个答案:

答案 0 :(得分:1)

尝试使用此包,看看它是否解决了它:

https://github.com/barryvdh/laravel-cors

我在使用自己的中间件失败后也使用了这个包