简体   繁体   中英

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

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', 'UserController@store');
});

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\UserController@store | 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?

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 ' ' and after i change it to ' ' (with the 's' at the back) '并在我将其更改为' '(后面的's')
then my API working like normal !

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

The real reason for my case is any interaction with any different server must use ' ' (This is the setup on my server) '(这是我服务器上的设置)

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('/','UserController@store');

    Route::get('/', 'UserController@index');

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

        Route::post('{user}', 'UserController@update');

    });
});

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

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'));

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=test@test.com" -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...

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!

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('/', 'IndexController@index')->middleware('auth:api'); }); 

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.

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

检查你的请求类型GET/POST/PUT/PATCH两侧,即前端Javascript/Typescript etc... )以及后端Laravel Passport )它应该是相同的。

In my case I didnt add Controller word to controller's name

Make sure you have "Accept":"application/json" in your header.

EG Accept: application/json User-Agent: Thunder Client ( https://www.thunderclient.io ) Content-Type: application/x-www-form-urlencoded

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM