标头不工作,显示空白页而不是404


Headers are not working, showing a blank page instead of 404

任何人都可以帮助我理解为什么抛出HTTP重定向的头不会在这段代码中工作?如果我的路由工作,那么它就会按预期显示页面。但是当路由不匹配(存在)时,它不会抛出404页面,只显示一个空白页面。

它可能与WAMP设置(Apache, PHP.ini)有关,还是与。htaccess文件有关?

我正在使用来自dannyvankooten @https://github.com/dannyvankooten/AltoRouter的AltoRouter类

谢谢!

前端控制器(index.php):

$router = new router();
$router->map('GET', '/welcome/', 'WelcomeController#hello', 'welcome_hello');
$match = $router->match();
if ($match === false)
{
    header("HTTP/1.0 404 Not Found");
}
else
{
    list($controller, $action) = explode('#', $match['target']);
    if (is_callable(array($controller, $action)))
    {
        $obj = new $controller();
        call_user_func_array(array($obj, $action), array($match['params']));
    }
    else
    {
        header("HTTP/1.0 500 Internal Server Error");
    }
}

。htaccess

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule . index.php [L]

我无法在我的本地机器上使用您的代码复制此内容。但是请注意,我必须做以下更改:

这个包的根类是new AltoRouter()而不是new router(),是否有一个小的机会,你有另一个路由器()类,可以有类似的方法?

标题可能仍然被设置为404,但没有提供自定义内容来显示在页面上。浏览器在不同的情况下显示不同的错误页面。在下面的示例中,我提供了一条自定义消息来进行确认。因为浏览器响应不同,可以缓存响应等。我是用Postman测试的,不过你也可以用很多其他的工具。

这个代码示例对我来说工作成功:

$router = new AltoRouter();
$router->map('GET', '/welcome/', 'WelcomeController#hello', 'welcome_hello');
$match = $router->match();
// var_dump($match); // dump or breakpoint/xdebug here to avoid testing other logic.
if ($match === false)
{
    header("HTTP/1.0 404 Not Found");
    echo "That URL doesn't exist";
} else {
    echo "Route matched!<br>";
    echo "<pre>".print_r($match, true)."</pre>";
}

和我运行的文件:php -S localhost:8088 alto_router.php

GET localhost:8088/Welcome -> 404
GET localhost:8088/welcome -> 404
GET localhost:8088/Welcome/ -> 404
GET localhost:8088/welcome/ -> 200