Hello everyone! I’m trying to handle the HTTP request HEAD using SLIM and it doesn’t seems to work like other methods. I can’t have $app->head like I would with GET, POST, PUT or DELETE.
What is the the (best) way to achieve this?
Thanks!
Hello everyone! I’m trying to handle the HTTP request HEAD using SLIM and it doesn’t seems to work like other methods. I can’t have $app->head like I would with GET, POST, PUT or DELETE.
What is the the (best) way to achieve this?
Thanks!
There is indeed no App::head
method.
You can use App::map
to create a route for requests using the HEAD method:
$app->map(['HEAD'], '/test-head', function(Request $request, Response $response) {
return $response->withHeader('X-Test', 'head');
});
Using App::any
will actually not work, as it will only match the methods GET, POST, PUT, PATCH, DELETE and OPTIONS.
It worked! Thanks a lot!
Is this still working in Slim 3 ?
I get error 500 when U use it like this.
Is there an other way to fix this?
Hello Dadinos,
This is still working in Slim 3.
The error 500 message is not very descriptive, so I have to guess what the cause of the error is. You may want to look in the web server error logs for a more detailed error message or turn on the display of error details as described here: System Error Handler - Slim Framework
Perhaps you have not added the use
statements to import the Request
and Response
classes?
Here is a more complete example to test this:
<?php
require_once __DIR__ . '/vendor/autoload.php';
use Psr\Http\Message\ServerRequestInterface as Request;
use Psr\Http\Message\ResponseInterface as Response;
$app = new \Slim\App();
$app->map(['HEAD'], '/test-head', function(Request $request, Response $response) {
return $response->withHeader('X-Test', 'head');
});
$app->run();
This is the output I get with curl:
$ curl -I -X HEAD localhost:8080/test-head
HTTP/1.1 200 OK
Host: localhost:8080
Date: Fri, 03 Jun 2022 08:02:11 GMT
Connection: close
X-Powered-By: PHP/8.1.2
Content-Type: text/html; charset=UTF-8
X-Test: head
Content-Length: 0
Thanks for your reaction llvdl,
I got all the use … and logging in place. Other Methods like GET and POST working well.
I have also set ‘displayErrorDetails’ => true and on my webserver (IIS) detailed error is selected in the error page settings.
I found out that when you have an error in your class function the error 500 is shown.
On a GET or POST the detailed errors are shown but on a HEAD not.
I this because it cannot output any content in a HEAD response and only return header information?