gpt4 book ai didi

php - 无法通过 jquery Ajax 在 laravel 5 中发布

转载 作者:可可西里 更新时间:2023-10-31 23:06:42 24 4
gpt4 key购买 nike

我试图在 Laravel 5.1 应用程序中通过 jquery Ajax 发送一个 POST 请求。我得到 405 方法不允许,我在这个论坛上搜索其他问题但没有找到解决方案:

我的routes.php:

Route::post('backend/get_subdirectories',  'Backend\FileManagerController@get_subdirectories');

Controller

public function get_subdirectories(Request $request)
{
dd($request);
}

和脚本

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");
});

我收到错误 405 - 方法不允许

我哪里错了?

最佳答案

@Chris 的评论是正确的:)

您只需要从网址末尾删除 /。您的 ajax 请求应该转到 http://domain.com/backend/get_subdirectories

原因是,因为在 public/.htaccess 文件中,它将 301 重定向所有带有尾部斜杠的 url 到没有斜杠的相同 url。执行此操作的代码在这里:

# Redirect Trailing Slashes If Not A Folder...
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)/$ /$1 [L,R=301]

现在真正的问题是,客户端将对 301 重定向指定的 URL 执行 GET 请求。

等等!为什么要这样做???

好吧,我们可以看看 RFC7231的答案。它说

6.4.2. 301 Moved Permanently

The 301 (Moved Permanently) status code indicates that the target
resource has been assigned a new permanent URI and any future
references to this resource ought to use one of the enclosed URIs.
Clients with link-editing capabilities ought to automatically re-linkreferences to the effective request URI to one or more of the new
references sent by the server, where possible.

The server SHOULD generate a Location header field in the responsecontaining a preferred URI reference for the new permanent URI. The
user agent MAY use the Location field value for automatic
redirection. The server's response payload usually contains a short
hypertext note with a hyperlink to the new URI(s).

  Note: For historical reasons, a user agent MAY change the request
method from POST to GET for the subsequent request. If this
behavior is undesired, the 307 (Temporary Redirect) status code
can be used instead.

A 301 response is cacheable by default; i.e., unless otherwise
indicated by the method definition or explicit cache controls (see
Section 4.2.2 of [RFC7234]).

现在有趣的是底部的注释指定用户代理可以将请求方法从 POST 更改为 GET。似乎从浏览器到框架的大多数用户代理似乎都遵循该规则。

关于php - 无法通过 jquery Ajax 在 laravel 5 中发布,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35565809/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com