Slim always returns 404

Hi everyone.

I’ve installed latest Slim version and created a new Slim Skeleton project as suggested in Slim Home Page. I’ve implemented a method in index.php, so my code looks like this:

<?php
declare(strict_types=1);

use App\Application\Handlers\HttpErrorHandler;
use App\Application\Handlers\ShutdownHandler;
use App\Application\ResponseEmitter\ResponseEmitter;
use DI\ContainerBuilder;
use Slim\Factory\AppFactory;
use Slim\Factory\ServerRequestCreatorFactory;

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

// Instantiate PHP-DI ContainerBuilder
$containerBuilder = new ContainerBuilder();

if (false) { // Should be set to true in production
	$containerBuilder->enableCompilation(__DIR__ . '/../var/cache');
}

// Set up settings
$settings = require __DIR__ . '/../app/settings.php';
$settings($containerBuilder);

// Set up dependencies
$dependencies = require __DIR__ . '/../app/dependencies.php';
$dependencies($containerBuilder);

// Set up repositories
$repositories = require __DIR__ . '/../app/repositories.php';
$repositories($containerBuilder);

// Build PHP-DI Container instance
$container = $containerBuilder->build();

// Instantiate the app
AppFactory::setContainer($container);
$app = AppFactory::create();
$callableResolver = $app->getCallableResolver();

// Register middleware
$middleware = require __DIR__ . '/../app/middleware.php';
$middleware($app);

// Register routes
$routes = require __DIR__ . '/../app/routes.php';
$routes($app);

/** @var bool $displayErrorDetails */
$displayErrorDetails = $container->get('settings')['displayErrorDetails'];

// Create Request object from globals
$serverRequestCreator = ServerRequestCreatorFactory::create();
$request = $serverRequestCreator->createServerRequestFromGlobals();

// Create Error Handler
$responseFactory = $app->getResponseFactory();
$errorHandler = new HttpErrorHandler($callableResolver, $responseFactory);

// Create Shutdown Handler
$shutdownHandler = new ShutdownHandler($request, $errorHandler, $displayErrorDetails);
register_shutdown_function($shutdownHandler);

// Add Routing Middleware
$app->addRoutingMiddleware();

// Add Error Middleware
$errorMiddleware = $app->addErrorMiddleware($displayErrorDetails, false, false);
$errorMiddleware->setDefaultErrorHandler($errorHandler);

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

// Run App & Emit Response
$response = $app->handle($request);
$responseEmitter = new ResponseEmitter();
$responseEmitter->emit($response);

I’m calling my method /hello/world but it always returns this JSON:

{
    "statusCode": 404,
    "error": {
        "type": "RESOURCE_NOT_FOUND",
        "description": "Not found."
    }
}

I’ve tried a lot of things, such as redefine the .htaccess file in a lot of different ways, replace my API code with the example located in Slim Home Page, etc.

What am I doing wrong? Thanks in advance for all your replies!

You should set the basePath if you run Slim in a sub-directory:

$app->setBasePath('my-sub-directory/');

There is also a library for Slim that helps to solve the basePath issue for Apache: basepath

Hello, odan! Thanks for your reply.

Unsuccessfully, those things you say didn’t work for me. It keeps throwing error 404. I have my API located in a subdirectory inside of a subdomain, I attach the path: /www/sub.domain.com/public_html/API

If /www/sub.domain.com/public_html is the webservers document root and your index.php is in API/ then the basePath should be API/.

$app->setBasePath('API/');

BTW: The BasepathMiddleware detects the correct basePath automatically for you.

Yeah, I tried to set the base path to that one, and I also tried with the BasepathMiddleware library, but it still throws a error 404…

Ok than it’s not easy.

Some things you could also try:

  1. This is not correct here. Remove this.
// Create Request object from globals
$serverRequestCreator = ServerRequestCreatorFactory::create();
$request = $serverRequestCreator->createServerRequestFromGlobals();
  1. Also remove this:
// Create Error Handler
$responseFactory = $app->getResponseFactory();
$errorHandler = new HttpErrorHandler($callableResolver, $responseFactory);

// Create Shutdown Handler
$shutdownHandler = new ShutdownHandler($request, $errorHandler, $displayErrorDetails);
register_shutdown_function($shutdownHandler);
  1. Add a route for ‘/’ to see if the root is working.
$app->get('/', function (Request $request, Response $response, array $args) {
    $response->getBody()->write("It works");
    return $response;
});
  1. This is not correct. Remove it.
// Run App & Emit Response
$response = $app->handle($request);
$responseEmitter = new ResponseEmitter();
$responseEmitter->emit($response);

Replace it with this:

$app->run();

Then test your “/” root url first to see if it works.

Thank you for your time, odan.

Changing that it throws now another error but this time it is not an HTTP Exception:


Slim Application Error

The application could not run because of the following error:

Details

Type: FastRoute\BadRouteException

Code: 0

Message: Cannot register two routes matching “/” for method “GET”

File: /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php

Line: 86

Trace

#0 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/nikic/fast-route/src/DataGenerator/RegexBasedAbstract.php(30): FastRoute\DataGenerator\RegexBasedAbstract->addStaticRoute(‘GET’, Array, ‘route3’) #1 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/nikic/fast-route/src/RouteCollector.php(44): FastRoute\DataGenerator\RegexBasedAbstract->addRoute(‘GET’, Array, ‘route3’) #2 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/slim/slim/Slim/Routing/Dispatcher.php(45): FastRoute\RouteCollector->addRoute(Array, ‘/’, ‘route3’) #3 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/nikic/fast-route/src/functions.php(25): Slim\Routing\Dispatcher->Slim\Routing{closure}(Object(FastRoute\RouteCollector)) #4 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/slim/slim/Slim/Routing/Dispatcher.php(61): FastRoute\simpleDispatcher(Object(Closure), Array) #5 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/slim/slim/Slim/Routing/Dispatcher.php(74): Slim\Routing\Dispatcher->createDispatcher() #6 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/slim/slim/Slim/Routing/RouteResolver.php(58): Slim\Routing\Dispatcher->dispatch(‘GET’, ‘/API/public/’) #7 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php(77): Slim\Routing\RouteResolver->computeRoutingResults(’/API/public/’, ‘GET’) #8 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/slim/slim/Slim/Middleware/RoutingMiddleware.php(59): Slim\Middleware\RoutingMiddleware->performRouting(Object(Slim\Psr7\Request)) #9 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/slim/slim/Slim/MiddlewareDispatcher.php(140): Slim\Middleware\RoutingMiddleware->process(Object(Slim\Psr7\Request), Object(class@anonymous)) #10 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/selective/basepath/src/BasePathMiddleware.php(52): class@anonymous->handle(Object(Slim\Psr7\Request)) #11 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/slim/slim/Slim/MiddlewareDispatcher.php(140): Selective\BasePath\BasePathMiddleware->process(Object(Slim\Psr7\Request), Object(class@anonymous)) #12 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/slim/slim/Slim/Middleware/ErrorMiddleware.php(107): class@anonymous->handle(Object(Slim\Psr7\Request)) #13 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/slim/slim/Slim/MiddlewareDispatcher.php(140): Slim\Middleware\ErrorMiddleware->process(Object(Slim\Psr7\Request), Object(class@anonymous)) #14 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/slim/slim/Slim/MiddlewareDispatcher.php(81): class@anonymous->handle(Object(Slim\Psr7\Request)) #15 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/slim/slim/Slim/App.php(215): Slim\MiddlewareDispatcher->handle(Object(Slim\Psr7\Request)) #16 /home/customer/www/dev.nicoteamstudios.com/public_html/API/vendor/slim/slim/Slim/App.php(199): Slim\App->handle(Object(Slim\Psr7\Request)) #17 /home/customer/www/dev.nicoteamstudios.com/public_html/API/public/index.php(68): Slim\App->run() #18 {main}


Maybe I have an error with path handling in my server?

Then you already had defined a route for “/”. It was not clear for me, because you havent posted it in your first question. Remove the second route for “/”. Please read this tutorial fpr Slim 4 and apache

1 Like

Wow, really good tutorial! Due to it, now I can have access to all my methods! This saved my project, thank you so much, odan!!! I’ll mark this topic as resolved

1 Like