首页 > 解决方案 > XAMPP 上的 Slim 应用程序抛出“未找到”异常

问题描述

我尝试在 XAMPP 上运行我的 Slim 框架项目,并使用来自 Slim 框架网站的 Apache 配置

当我打开这个 URL http://localhost:8081/SlimAPIProject/public/hello/ayad 我得到这个错误:

Fatal error: Uncaught Slim\Exception\HttpNotFoundException: Not found. in C:\xampp\htdocs\SlimAPIProject\vendor\slim\slim\Slim\Middleware\RoutingMiddleware.php:93 Stack trace:
#0 C:\xampp\htdocs\SlimAPIProject\vendor\slim\slim\Slim\Routing\RouteRunner.php(72): Slim\Middleware\RoutingMiddleware->performRouting(Object(Slim\Http\ServerRequest))
#1 C:\xampp\htdocs\SlimAPIProject\vendor\slim\slim\Slim\MiddlewareDispatcher.php(81): Slim\Routing\RouteRunner->handle(Object(Slim\Http\ServerRequest))
#2 C:\xampp\htdocs\SlimAPIProject\vendor\slim\slim\Slim\App.php(211): Slim\MiddlewareDispatcher->handle(Object(Slim\Http\ServerRequest))
#3 C:\xampp\htdocs\SlimAPIProject\vendor\slim\slim\Slim\App.php(195): Slim\App->handle(Object(Slim\Http\ServerRequest))
#4 C:\xampp\htdocs\SlimAPIProject\public\index.php(16): Slim\App->run()
#5 {main} thrown in C:\xampp\htdocs\SlimAPIProject\vendor\slim\slim\Slim\Middleware\RoutingMiddleware.php on line 93

这是我的 index.php

<?php
use Psr\Http\Message\ResponseInterface as Response;
use Psr\Http\Message\ServerRequestInterface as Request;
use Slim\Factory\AppFactory;

require __DIR__ . '/../vendor/autoload.php';

$app = AppFactory::create();

$app->get('/hello/{name}', function (Request $request, Response $response, array $args) {
    $name = $args['name'];
    $response->getBody()->write("Hello, $name");
    return $response;
});

$app->run();

标签: .htaccessxamppslim

解决方案


如果您在 Web 根目录的子目录中运行 Slim,则可能会发生这种情况。Slim 需要知道 URL 的哪一部分应该被视为您的应用程序的基本 URL,以便之后的所有内容都将被视为路由。

我已经看到了很多解决方案,但没有一个对我有用。

此外,您希望您的应用程序是可移植的,这样当您部署它时,您就不需要摆弄一些跨服务器不同的设置。所以我想出了以下解决方案,它不需要在主 Slim 应用程序的入口点之外进行任何更改。

<?php

...

// Instantiate App
$app = AppFactory::create();

// Set the base path of the Slim App
$basePath = str_replace('/' . basename(__FILE__), '', $_SERVER['SCRIPT_NAME']);
$app = $app->setBasePath($basePath);


这将动态计算应用作基础浴的值,即使您将脚本移动到另一个位置或重命名它也将起作用。


推荐阅读