Slim v3 not throwing 405 error when a GET request is made on a POST endpoint


#1

In case of a plain endpoint, that is devoid of any path_params, and registered as POST, slim framework is allowing a GET call on it too, instead of throwing a 405 Not Allowed error.

For example,

$app->post("/customer/register", CustomerController::class . ":register");
accepts both GET and POST (should have allowed post only and thrown a 405 in case of a GET)

The problem is solved when a parameter is added to the path as below
$app->post("/customer/register/{customer_id}", CustomerController::class . ":register");

Any idea how this can be resolved ??? or why this is happening ?


#2

I suspect you have another route that is matching you were not expecting. I’ve tried to duplicate this but my results didn’t match yours. Here is my app

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

// Create and configure Slim app
$config = ['settings' => [
    'addContentLengthHeader' => false,
]];
$app = new \Slim\App($config);

// Define app routes
$app->post('/customer/register', function ($request, $response, $args) {
    return $response->write("Hello");
});

// Run app
$app->run();

And my request

## Request
curl -X "POST" "http://slim.localhost:8080/customer/register"

And the response

HTTP/1.1 405 METHOD NOT ALLOWED
Server: Apache
Content-Type: text/html;charset=UTF-8
X-Powered-By: PHP/7.0.25
Allow: POST
Date: Wed, 23 May 2018 12:23:51 GMT
X-Frame-Options: SAMEORIGIN
Content-Length: 556
Keep-Alive: timeout=5, max=100
Connection: Keep-Alive

<html>
    <head>
        <title>Method not allowed</title>
        <style>
            body{
                margin:0;
                padding:30px;
                font:12px/1.5 Helvetica,Arial,Verdana,sans-serif;
            }
            h1{
                margin:0;
                font-size:48px;
                font-weight:normal;
                line-height:48px;
            }
        </style>
    </head>
    <body>
        <h1>Method not allowed</h1>
        <p>Method not allowed. Must be one of: <strong>POST</strong></p>
    </body>
</html>

#3

Thanks for the reply.
I suspected that in the beginning too, double checked all the paths. But could not find any conflicts.
Could you please share the exact slim version you’re using. Maybe there’s a bug in mine.


#4

I’m using version 3.10.0


#5

Thanks! Will try it out


#6

Comment out all of your routes except for that one POST route and see if you get the same result. That will tell you if another route is matching.


#7

Got the problem and thanks to you for pointing it out
I had another path like
/api/customer/{customer_id} accepting GET

This was interfering with
/api/customer/register accepting POST

I’ve changed this to
/api/customer/register/
so that it becomes unique.

Once again huge thanks for helping me out. CHEERS


#8

Great, glad you got it sorted out!