简体   繁体   中英

How do I serve my index.html file while using PHP Slim REST Api?

I'm getting started with PHP Slim, I'm creating a REST API, and I'd like to put a client in front of that.

It's a simple question, but I can't figure out how to serve my index.html (the client's home page).

I'm starting my slim app using the command in the Slim tutorial: php -S localhost:8888 -t api index.php , but I get a 404 when I get a try to navigate to index.html.

I know I can render a home state in Slim which serves index.html, but is there another way to do it that doesn't have my API serve a template? In other words, is there a way I can navigate directly to my client?

api
  index.php
public
  index.html

And currently I'm using the command, php -S localhost:8888 -t api index.php to start my server

Currently you setting you document root to /api so there is actual no way to access the html file without using php code for including the html file. Because the file is before the document root ( /api )

In my opinion the best option would be to add a route in slim for that and include the index.html from the client in it and then show it

$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 \Slim\Exception\NotFoundException($request, $response);
    }
})

You could also do something like this:

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

When you then start the php server with out the file and path php -S localhost:8888

the client could be accessed with domain.com/ and the api with domain.com/api/

Note: you should use the php server only for testing and not in production.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM