简体   繁体   中英

Laravel API Routes Return 404

I am using Laravel 5.6 and I'm getting HTTP404 responses on existing routes in routes/api.php which I define as follows:

Route::middleware('auth:api')->post('/account/plan', 'Account\BillingController@updatePlan');
Route::middleware('auth:api')->put('/account/plan', 'Account\BillingController@unsubscribe');
Route::middleware('auth:api')->patch('/account/plan', 'Account\BillingController@resubscribe');

When I use axios.post() on these routes and include the _method parameter I get a 404 response on the PUT and PATCH routes. I have also tested axios.put()/axios.patch() in place of using post() with and without the inclsion of the _method parameter. I have also confirmed these are being correctly represented by artisan route:list:

|        | POST          | api/account/plan                        |                    | App\Http\Controllers\Account\BillingController@updatePlan                 | api,auth:api |
|        | PUT           | api/account/plan                        |                    | App\Http\Controllers\Account\BillingController@unsubscribe                | api,auth:api |
|        | PATCH         | api/account/plan                        |                    | App\Http\Controllers\Account\BillingController@resubscribe                | api,auth:api |

Example of the Axios Call:

axios.post(url,{_method:"PUT",confirm:"unsubscribe"})
     .then(response => callback(response.data))
     .catch(error => console.log(error))

When I define these same routes as follows they all work as intended:

Route::middleware('auth:api')->post('/account/plan', 'Account\BillingController@updatePlan');
Route::middleware('auth:api')->post('/account/unsubscribe', 'Account\BillingController@unsubscribe');
Route::middleware('auth:api')->post('/account/resubscribe', 'Account\BillingController@resubscribe');

I am able to separate endpoints by the request method on other routes I am unsure why these are creating a problem. Can someone explain why I get the 404 responses and how I can avoid them?

Since it seems you are doing evrything fine maybe by following laravel more strict conventions on defining routes you won't encounter the problem? Try like this:

Route::middleware(['auth:api'])->group(function () {
    Route::post('/account/plan', 'Account\BillingController@updatePlan');
    Route::put('/account/plan', 'Account\BillingController@unsubscribe');
    Route::patch('/account/plan', 'Account\BillingController@resubscribe');
});

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