如何在使用 PHP Slim REST API 时提供我的索引.html文件



我正在开始使用PHP Slim,我正在创建一个REST API,我想在它前面放一个客户端。

这是一个简单的问题,但我无法弄清楚如何提供我的索引.html(客户的主页)。

我正在使用 Slim 教程中的命令启动我的苗条应用程序:php -S localhost:8888 -t api index.php ,但是当我尝试导航到 index.html 时,我得到了 404。

我知道我可以在 Slim 中呈现一个提供索引.html的home状态,但是有没有另一种方法可以让我的 API 提供模板?换句话说,有没有办法直接导航到我的客户?

api
  index.php
public
  index.html

目前我正在使用命令,php -S localhost:8888 -t api index.php启动我的服务器

目前您将文档 root 设置为 /api 因此,如果不使用 php 代码来包含 html 文件,实际上无法访问 html 文件。因为文件在文档根目录之前(/api

在我看来,最好的选择是为此添加一个苗条的路由,并在其中包含来自客户端的索引.html然后显示它

$app->get('/clientindex', function ($request, $response, $args) {
    $file = '../public/index.html';
    if (file_exists($file)) {
        return $response->write(file_get_contents($file));
    } else {
        throw new SlimExceptionNotFoundException($request, $response);
    }
})

你也可以做这样的事情:

/api
    /index.php // do slim stuff
index.html // display client

然后启动 php 服务器时,不带文件和路径php -S localhost:8888

可以使用domain.com/访问客户端,可以使用domain.com/api/访问 API

注意:您应该仅将 php 服务器用于测试,而不是在生产中使用。

最新更新