.htaccess - 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();
解决方案
如果您在 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);
这将动态计算应用作基础浴的值,即使您将脚本移动到另一个位置或重命名它也将起作用。
推荐阅读
- swift - 从对象引用值类型以供以后突变的安全方法
- apache - 如何使用 htaccess 从 url 中删除不必要的查询字符串参数?
- c# - UNET 传输级 API 高效的消息处理和类型
- c# - 如何将双倍提高 3%
- php - 如何使用 php、codeigniter 从文件夹中仅获取 .txt 格式文件列表
- tensorflow - 如何在 Keras 中设置内核初始化程序(glorot_uniform)的种子值
- python - 在 Python 上使用 Tesseract-OCR 的问题
- mysql - 即使该月没有记录,如何从查询中获取所有月份?
- javascript - 在 MAC OS High Sierra 中为 npm 设置代理后,每个 NPM 命令都返回错误
- javascript - 我什么时候应该在javascript中的require('module')之后使用点(。)