【问题标题】:CORS header error when Angular use for front end and Laravel used for BackendAngular 用于前端而 Laravel 用于后端时出现 CORS 标头错误
【发布时间】:2017-06-20 11:20:10
【问题描述】:

我正在使用 angular 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 令牌的发布请求,因此它可以完美运行。我得到了令牌作为回应。然后我将它存储到会话中并使用拦截器在所有请求的标头中设置令牌。

我的控制器看起来像:

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.

【问题讨论】:

    标签: angularjs laravel cors


    【解决方案1】:

    尝试使用这个包看看它是否解决它:

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

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

    【讨论】:

    • 感谢它的工作。但是你知道为什么我的 cors 中间件不工作吗?以及在使用GET请求方法时如何防止GET方法在angular js中转换为OPTION
    猜你喜欢
    • 2018-11-23
    • 2017-12-01
    • 2020-11-05
    • 2023-03-11
    • 2021-06-20
    • 1970-01-01
    • 2019-02-17
    • 2021-03-09
    • 2021-03-12
    相关资源
    最近更新 更多