Laravel 5 POST routes to index instead of store

2019-02-13 21:11发布

问题:

I am working on a Laravel 5 RESTful API that seems not to be routing the POST requests correctly.

This is my routes.php:

Route::group(array('prefix' => 'api/v1'), function()
{
    Route::resource('messages', 'IncomingMessages');
});

And this is my controller:

class IncomingMessages extends Controller
{   
    public function index() {
        return "This is index";
    }

    public function store() {
        return "This is store";
    }

    public function update() {
        return "This is update";
    }
}

And this is what happens:

  • Request GET mydomain.com/api/v1/messages/ --> This is index
  • Request PUT mydomain.com/api/v1/messages/1 --> This is update
  • Request POST mydomain.com/api/v1/messages/ --> This is index

This is what php artisan route:list returns:

  • GET|HEAD : api/v1/messages : api.v1.messages.index : App\Http\Controllers\IncomingMessages@index
  • GET|HEAD : api/v1/messages/create : api.v1.messages.create : App\Http\Controllers\IncomingMessages@create
  • POST : api/v1/messages : api.v1.messages.store : App\Http\Controllers\IncomingMessages@store
  • GET|HEAD : api/v1/messages/{messages} : api.v1.messages.show : App\Http\Controllers\IncomingMessages@show
  • GET|HEAD : api/v1/messages/{messages}/edit : api.v1.messages.edit : App\Http\Controllers\IncomingMessages@edit
  • PUT : api/v1/messages/{messages} :api.v1.messages.update ; App\Http\Controllers\IncomingMessages@update
  • PATCH : api/v1/messages/{messages} : App\Http\Controllers\IncomingMessages@update
  • DELETE : api/v1/messages/{messages} : api.v1.messages.destroy : App\Http\Controllers\IncomingMessages@destroy

So, my question is:

What am I missing? Why is it routing to index() instead of routing to store()?

NOTES:

  • I have disabled "VerifyCsrfToken" in Kernel.php
  • I am trying the requests using Chromium plugin "Postman".

UPDATE:

The problem was adding a trailing / to the URL. So, instead of using this URL:

mydomain.com/api/v1/messages/

I tried with this one:

mydomain.com/api/v1/messages

and it worked

回答1:

The problem was caused by a trailing / being added to the URL. So, instead of using this URL:

mydomain.com/api/v1/messages/

I tried with this one:

mydomain.com/api/v1/messages

and it worked.

I discovered it by taking a look at the server's log. That is how I discovered that POST requests to the URL messages/ were redirected.