I'm trying to send a POST
request over jquery Ajax in Laravel 5.1 application. I got 405 method not allow, I'm search other questions on this forum but not find solution:
My routes.php
:
Route::post('backend/get_subdirectories', 'Backend\FileManagerController@get_subdirectories');
The Controller
public function get_subdirectories(Request $request)
{
dd($request);
}
And script
var _token = $('meta[name="csrf-token"]').attr('content');
console.log(_token); //It work, I can get my token from meta tag
$.post(
'http://domain.com/backend/get_subdirectories/',
{ _token: _token},
function () {
alert("success");
})
.fail(function () {
alert("error");
})
.always(function () {
alert("finished");
});
And I got error 405 - Method not allowed
What am I wrong ?
@Chris's comment is correct :)
You simply need to remove the
/
from the end of your url. Your ajax request should go tohttp://domain.com/backend/get_subdirectories
.The reason is, because within the
public/.htaccess
file it will 301 redirect all urls with a trailing slash to the same url without one. The code that does it is here:Now the real issue is, the client will preform a GET request to the URL specified by the 301 redirect.
Wait! Why would it do this???
Well, we can look to RFC7231 for the answer. It says
Now what's interesting is the note at the bottom that specifies that the user agent MAY change the request method from POST to GET. And it seems most user agents from browsers to frameworks, seem to follow that rule.