405 Method not allowed error in laravel Lumen resolved.

What is 405 Method Not Allowed?

The 405 Method not allowed is an HTTP response status code that indicates that the method received in the request is known by the origin server but not supported by the target resource. There can be different causes of this error but all are related to the way we have defined routes and configured middleware in lumen. A common cause of this error is when we do not access a method in the way it is defined in routes.

Let’s see below example.

$app->group(['prefix' => 'api/v1'], function($app)
{
    $app->get('users','UserController@index');
    $app->post('users','UserController@userlist');
});

In this example both routes are same but method types are different. If you are trying to access route which has GET method and posting data using POST method or doing vice- versa in such scenario lumen will throw error 405 Method not allowed.

So you need to make sure that you are accessing the methods in the correct way. i.e You must post data using correct method as defined in your routes in web.php file.

The 405 Method not allowed also occurs when No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

In Lumen framework you can create your own class to handle Access-Control-Allow-Origin errors where we will define all allowed methods. You need to define all the methods in this class that you are going to use.

Just create a new class in the app/Http/Middleware folder CorsMiddleware.php and add the below code.

<?php
namespace App\Http\Middleware;
use Closure;
class CorsMiddleware
{
/**
* Handle an incoming request.
*
* @param  \Illuminate\Http\Request  $request
* @param  \Closure  $next
* @return mixed
*/
    public function handle($request, Closure $next)
    {
        $headers = [
        'Access-Control-Allow-Origin'      => '*',
        'Access-Control-Allow-Methods'     => 'POST, GET, 
        OPTIONS,PUT,DELETE',
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age'           => '86400',
        'Access-Control-Allow-Headers'     => 'Content-Type, Authorization, 
        X-Requested-With'
        ];

        if ($request->isMethod('OPTIONS'))
        {
            return response()->json('{"method":"OPTIONS"}', 200, $headers);
        }

        $response = $next($request);
        foreach($headers as $key => $value)
        {
            $response->header($key, $value);
        }

        return $response;
    }
}

Once the class is created you need register your new middleware. For that add below code in app file in the bootstrap/app.php file.

$app->middleware([
    App\Http\Middleware\CorsMiddleware::class
 ]);

Try to run you API after all above changes. I hope this resolves the issue. Thank you.

About the Author: allcodebuzz

You might like

1 Comment

Leave a Reply

Your email address will not be published. Required fields are marked *