Home » Php » php – Laravel 5.2: POST request is always returning "405 Method Not Allowed"

php – Laravel 5.2: POST request is always returning "405 Method Not Allowed"

Posted by: admin July 12, 2020 Leave a comment

Questions:

So I am developing an API with Laravel 5.2 and I’m facing an important issue.

I have a UserController that will manage the users of my app.

This is my routes.php file:

Route::group(array('prefix' => 'api/v1'), function() {    
   Route::post('user', '[email protected]');
});

And I have my UserController defined like that:

class UserController extends Controller {

   public function index() {
       return 'Hello, API';
   }

   public function create(){
   }

   public function store(Request $request) {
       $user = new User;
       $user->email = $request->email;
       $user->password = $request->password;
       $user->fbId = $request->fbId;
       $user->ggId = $request->ggId;
       $user->firstName = $request->firstName;
       $user->lastName = $request->lastName;
       $user->imageUrl = $request->imageUrl;
       $user->country = $request->country;
       $user->mobile = $request->mobile;
       $user->gender = $request->gender;
       $user->client = $request->client;

       $user->save();

       return Response::json(array(
           'error' => false,
           'userId' => $user->id),
           200
       );
   }

   public function update(Request $request, $id) {
   }
}

And this is the output of php artisan route:list

+--------+--------+-------------+------+-------------------------------------------+------------+
| Domain | Method | URI         | Name | Action                                    | Middleware |
+--------+--------+-------------+------+-------------------------------------------+------------+
|        | POST   | api/v1/user |      | App\Http\Controllers\[email protected] | web        |
+--------+--------+-------------+------+-------------------------------------------+------------+

I’m using Postman to test my POST requests.
Every time I make a POST request to /api/v1/user, I get a “405 Method Not Allowed” error.

Did I miss anything?

Is there anything I should do to fix this issue?

How to&Answers:

I have same problem with you which are I already set in my POST route for example “/api/v1/user”,

and when I try to connect using POSTMAN (application to test API) , it return 405-Method Not Allowed,

and then i realize the url i was sent is using ‘http‘ and after i change it to ‘https‘ (with the ‘s’ at the back)
then my API working like normal !

normally if we interact with different server , we must use ‘https
but if your application at the same server ,
it’s okay to use ‘http

The real reason for my case is any interaction with any different server must use ‘https‘ (This is the setup on my server)

Answer:

You need to separate your routes because all the users trying to get to your routes need a open session (logged in)

Try this

Route::group(array('prefix' => 'api/v1'), function() {

    Route::post('/','[email protected]');

    Route::get('/', '[email protected]');

    Route::group(array('before' => 'auth.basic'), function() {

        Route::post('{user}', '[email protected]');

    });
});

Your authorized users routes should be in the second group

And your 405 Method not Allowed is $user->id change it for $request->user()->id

Answer:

Missing CSRF token

I had the same issue on Laravel 5.8 when creating web-hooks routes.

These routes use the web middleware and because of that, the VerifyCsrfToken route middleware group is also included. (Reference app/Http/Kernel.php)

Because my POST request doesn’t include a CSRF token we get this strange behaviour.

Add CSRF exception

To fix this, I needed to add an exception to the VerifyCsrfToken middleware for the web-hooks routes. (Reference app/Http/Middleware/VerifyCsrfToken.php)

/**
 * The URIs that should be excluded from CSRF verification.
 *
 * @var array
 */
protected $except = [
    'web-hooks/*'
];

Use API middleware

The above solution is for when the web middleware is used. However if you are creating API routes, it is better to use the api middleware instead because no CSRF verification is used in this middleware. (Reference app/Providers/RouteServiceProvider.php)

    Route::prefix('api')
        ->middleware('api')
        ->namespace($this->namespace)
        ->group(base_path('routes/api.php'));

Answer:

Changing to https will cause it to work. At least, that is what I have experienced. Using POSTman with http always has this effect.

Answer:

Faced something similar before, after debugging turns out it’s Postman problem and nothing related to the code!

So open your terminal and try making the same request with curl:

curl -X POST -H "Accept: application/json" -F "[email protected]" -F "password=secret" -F "firstName=Mahmoud"  -F "lastName=Zalt" ....... "http://your-domain.com/api/v1/user"

If this worked means you have to change few settings with Postman itself.
Really can’t remember what I did to it! But it’s something as simple as changing some default headers or removing the Authorization type…

Answer:

This error can also be caused by a request body that’s too large. In my case, I was accidentally sending an object with many sub-objects that all had many other sub-objects. Pruning my request data solved the issue.

Answer:

If it helps anyone I had this exact same problem; for some reason a combination of things fixed it.

  1. The obvious point was that it would return a NotFoundHttpException in RouteCollection.php line 161 this was due to me not sending my “api_token” in my post request.
  2. For some reason (I don’t know if this made a difference) but chaining my middleware worked instead of putting it in the Route:group I did;

    Route::group(['prefix'=>'api/v1'], function () {
        Route::post('/', '[email protected]')->middleware('auth:api');
    });
    

Answer:

Check your request type GET/POST/PUT/PATCH in both side
i.e. frontend(Javascript/Typescript etc...) as well as backend(Laravel Passport) it should be same.

Answer:

After long hours of digging and digging, I couldn’t find any solution to my problem.

I had to create a new Laravel project from scratch and add everything I had in my old project. To my surprise, everything worked perfectly and I still don’t understand why!

Anyways, thanks to all who tried to help on this 🙂 Cheers!