简体   繁体   中英

Laravel 5.4: POST API routes give MethodNotAllowedHttpException

It's so strange that the POST API routes doesn't work! Check this simple POST route in api.php :

// This route doesn't work!
Route::post('/test', function (Request $request) {
        return 'test';
});

It gives me this error: Symfony\\\\Component\\\\HttpKernel\\\\Exception\\\\MethodNotAllowedHttpException !

But if I change the request verb to GET, then both GET and POST work just fine!!! It's making me crazy!

// This route works on both, GET and POST!
Route::get('/test', function (Request $request) {
        return 'test';
});

And yes, as you know the API routes simply don't use the VerifyCsrfToken middleware. So the middleware is not the issue obviously! And php artisan cache:clear is not also the answer :(

Did anybody had the same problem? Any help would be so appreciated.

Oh yea! As @patricus also mentioned in comments, I was experimenting a stupid redirect without knowing it! Let me clear this for anyone else who is experienicng the same thing and don't know where this issue is coming from!

You need to make sure the URL that you're connecting to is not going to be redirected behind the scenes whatsoever...

eg in my own hosting panel, I have set to add WWW in all of my URLs... So when I was trying to access the https://example.com/app/public/api/test URL by POST method, I was getting the MethodNotAllowedHttpException error! Because my URL was redirecting to https://www.example.com/app/public/api/test and in redirection it will change to GET! And as I didn't set any GET routes... So obviously I was getting the MethodNotAllowedHttpException exception :)

That's stupid, right? Yea, I know! Also make sure if your app is on a SSL domain, always connect to https:// instead of http:// . Because it is not only secure but also a redirection may happen again, without you knowing it! How? By your own .htaccess file that you have changed or your hosting support has changed it for you and you don't remember (check this answer as well):

# Let's force using SSL on all of our URLs and also forbid non-secure POSTs

RewriteEngine On

# Forbid non-secure POSTs
RewriteCond %{HTTPS} !=on
RewriteCond %{REQUEST_METHOD} =POST
RewriteRule ^ / [F,L]

# Force SSL
RewriteCond %{HTTPS} !=on
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

Or by services such as CloudFlare , which help you be more secure and redirects all of your URLs from http:// to https:// if you have set this setting in your CloudFlare panel and again you don't remember that!

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