Header not set - SlimFramework

孤人 提交于 2019-12-11 06:26:56

问题


I use SlimFramework

When i run my script locali with xampp it works fine. But i uploaded the script to the server and now it cone the error that the header was not set.

XHR does not allow payloads for GET request. or change a method definition in settings.

Here the script in angular

$rootScope.globals = $cookies.getObject('globals') || {};
    if ($rootScope.globals.currentUser) {
        $http.defaults.headers.common['Authorization'] = 'Basic ' + $rootScope.globals.currentUser.token;
    }

$rootScope.$on('$locationChangeStart', function (event, next, current) {
        var restrictedPage = $.inArray($location.path(), ['/login', '/register', '/password']) === -1;
        var loggedIn = $rootScope.globals.currentUser;
        if (restrictedPage) {
            if (!loggedIn) {
                $location.path('/login');
            } else {
                UserService.checkToken($rootScope.globals.currentUser.token)
                    .then(function (response) {
                        if (!response.success) {
                            $location.path('/login');
                        }
                    });

            }
        }
    });

function checkToken(token) {
        return $http.get('api/v1/token').then(handleCallback, handleCallback);
    }
function handleCallback(res) {
        console.log(res);
        return res.data;
    }

And here the script with SlimFramework

$config['displayErrorDetails'] = true;
$config['addContentLengthHeader'] = false;
$config['determineRouteBeforeAppMiddleware'] = true;

$app = new \Slim\App(["settings" => $config]);
$container = $app->getContainer();

// This is the middleware
// It will add the Access-Control-Allow-Methods header to every request


$app->add(function ($req, $res, $next) {
    $response = $next($req, $res);
    return $response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});


$app->get('/token', function ($request, $response){
    $token = $request->getHeaderLine('Authorization');
    if($token){
        $db = new DbOperation();
        if($db->checkAuthentication($token)){
            $return = $response->withJson(["success"=> true], 200);
        } else {
            $return = $response->withJson([
                "success"=> false,
                "message"=>'Invalid token'
            ], 403);
        }
    } else {
        $return = $response->withJson([
            "success"=> false,
            "message"=>'Header not set.'
        ], 403);
    }
    return $return;
});

Whats my Problem? Everyone knows?

Thx

UPDATE: Get request

The response from API testing

HTTP/1.1 403 Forbidden
Server: nginx
Date: Mon, 27 Mar 2017 11:57:27 GMT
Content-Type: application/json;charset=utf-8
Transfer-Encoding: chunked
Connection: keep-alive
X-Powered-By: PHP/5.6.30
Access-Control-Allow-Origin: *
Access-Control-Allow-Headers: X-Requested-With, Content-Type, Accept, Origin, Authorization
Access-Control-Allow-Methods: GET
X-Powered-By: PleskLin

回答1:


if you want to open the api to cors call to every possible origin(test only) try this:

$app->add(function ($req, $res, $next) {
    $response = $next($req, $res);
    return $response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});

Or there is this Middleware that do the same: https://github.com/palanik/CorsSlim




回答2:


If you are not sure what is the header name generated by NG, you can debug the header sent to SLIM. In SLIM, it can be done like this:

$headers = $request->getHeaders();
foreach ($headers as $name => $values) {
    echo $name . ": " . implode(", ", $values);
}

Im using jquery, I set token in header globally, like this:

 $.ajaxPrefilter(function( options, oriOptions, jqXHR ) {
    jqXHR.setRequestHeader("Authorization", sessionStorage.token);
 }); 

That will send a token with a header name:

HTTP_AUTHORIZATION

To get specific header variable:

   $token_array = $request->getHeader('HTTP_AUTHORIZATION');

   if (count($token_array) == 0) {
       $data = Array(
            "jwt_status" => "token_not_exist"
        );  

        return $response->withJson($data, 401)
                        ->withHeader('Content-type', 'application/json');                   
   }

    $token = $token_array[0];


来源:https://stackoverflow.com/questions/43042221/header-not-set-slimframework

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!