php Laravel 5.2:POST 请求总是返回“405 Method Not Allowed”

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37836223/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:25:01  来源:igfitidea点击:

Laravel 5.2: POST request is always returning "405 Method Not Allowed"

phpapilaravelpost

提问by Joseph El Khoury

So I am developing an API with Laravel 5.2 and I'm facing an important issue.

所以我正在使用 Laravel 5.2 开发 API,我面临一个重要问题。

I have a UserController that will manage the users of my app.

我有一个 UserController 将管理我的应用程序的用户。

This is my routes.php file:

这是我的 routes.php 文件:

Route::group(array('prefix' => 'api/v1'), function() {    
   Route::post('user', 'UserController@store');
});

And I have my UserController defined like that:

我的 UserController 定义如下:

class UserController extends Controller {

   public function index() {
       return 'Hello, API';
   }

   public function create(){
   }

   public function store(Request $request) {
       $user = new User;
       $user->email = $request->email;
       $user->password = $request->password;
       $user->fbId = $request->fbId;
       $user->ggId = $request->ggId;
       $user->firstName = $request->firstName;
       $user->lastName = $request->lastName;
       $user->imageUrl = $request->imageUrl;
       $user->country = $request->country;
       $user->mobile = $request->mobile;
       $user->gender = $request->gender;
       $user->client = $request->client;

       $user->save();

       return Response::json(array(
           'error' => false,
           'userId' => $user->id),
           200
       );
   }

   public function update(Request $request, $id) {
   }
}

And this is the output of php artisan route:list

这是输出 php artisan route:list

+--------+--------+-------------+------+-------------------------------------------+------------+
| Domain | Method | URI         | Name | Action                                    | Middleware |
+--------+--------+-------------+------+-------------------------------------------+------------+
|        | POST   | api/v1/user |      | App\Http\Controllers\UserController@store | web        |
+--------+--------+-------------+------+-------------------------------------------+------------+

I'm using Postman to test my POST requests. Every time I make a POST request to /api/v1/user, I get a "405 Method Not Allowed" error.

我正在使用 Postman 来测试我的 POST 请求。每次我向 /api/v1/user 发出 POST 请求时,都会收到“405 Method Not Allowed”错误。

Did I miss anything?

我错过了什么吗?

Is there anything I should do to fix this issue?

我应该做些什么来解决这个问题?

回答by bathulah mahir

I have same problem with you which are I already set in my POST route for example "/api/v1/user",

and when I try to connect using POSTMAN (application to test API) , it return 405-Method Not Allowed,

我和你有同样的问题,我已经在我的 POST 路由中设置了例如“/api/v1/user”,

当我尝试使用 POSTMAN(应用程序测试 API)连接时,它返回 405-Method Not Allowed,

and then i realize the url i was sent is using 'http' and after i change it to 'https' (with the 's' at the back)
then my API working like normal !

然后我意识到我发送的 url 使用的是“ http”,在我将其更改为“ https”(后面是“s”)
之后,我的 API 正常工作!

normally if we interact with different server , we must use 'https'
but if your application at the same server ,
it's okay to use 'http'

The real reason for my case is any interaction with any different server must use 'https' (This is the setup on my server)

通常,如果我们与不同的服务器交互,我们必须使用“ https”,
但如果您的应用程序在同一台服务器上,
则可以使用“ http

我的情况的真正原因是与任何不同服务器的任何交互都必须使用“ https”(这是我服务器上的设置)

回答by Enmy Pérez Moncada

You need to separate your routes because all the users trying to get to your routes need a open session (logged in)

您需要分开您的路线,因为所有试图到达您的路线的用户都需要一个开放的会话(已登录)

Try this

尝试这个

Route::group(array('prefix' => 'api/v1'), function() {

    Route::post('/','UserController@store');

    Route::get('/', 'UserController@index');

    Route::group(array('before' => 'auth.basic'), function() {

        Route::post('{user}', 'UserController@update');

    });
});

Your authorized users routes should be in the second group

您的授权用户路由应该在第二组中

And your 405 Method not Allowed is $user->idchange it for $request->user()->id

并且您的 405 Method not Allowed$user->id将其更改为$request->user()->id

回答by Bram Verstraten

Missing CSRF token

缺少 CSRF 令牌

I had the same issue on Laravel 5.8 when creating web-hooksroutes.

创建web-hooks路由时,我在 Laravel 5.8 上遇到了同样的问题。

These routes use the web middlewareand because of that, the VerifyCsrfToken route middleware groupis also included. (Reference app/Http/Kernel.php)

这些路由使用web 中间件,因此,VerifyCsrfToken 路由中间件组也包括在内。(参考app/Http/Kernel.php

Because my POST request doesn't include a CSRF tokenwe get this strange behaviour.

因为我的 POST 请求不包含CSRF 令牌,所以我们得到了这种奇怪的行为。

Add CSRF exception

添加CSRF异常

To fix this, I needed to add an exceptionto the VerifyCsrfToken middlewarefor the web-hooks routes. (Reference app/Http/Middleware/VerifyCsrfToken.php)

为了解决这个问题,我需要为 Web 钩子路由的 VerifyCsrfToken 中间件添加一个例外。(参考app/Http/Middleware/VerifyCsrfToken.php

/**
 * The URIs that should be excluded from CSRF verification.
 *
 * @var array
 */
protected $except = [
    'web-hooks/*'
];

Use API middleware

使用 API 中间件

The above solution is for when the web middleware is used. However if you are creating API routes, it is better to use the api middleware instead because no CSRF verification is used in this middleware. (Reference app/Providers/RouteServiceProvider.php)

上面的解决方案是针对使用web中间件时的。但是,如果您正在创建 API 路由,最好使用 api 中间件,因为该中间件中没有使用 CSRF 验证。(参考app/Providers/RouteServiceProvider.php

    Route::prefix('api')
        ->middleware('api')
        ->namespace($this->namespace)
        ->group(base_path('routes/api.php'));

回答by anabeto93

Changing to https will cause it to work. At least, that is what I have experienced. Using POSTman with http always has this effect.

更改为 https 将使其工作。至少,这是我所经历的。将 POSTman 与 http 一起使用始终具有此效果。

回答by Ajit Das

Check your request type GET/POST/PUT/PATCHin both side i.e. frontend(Javascript/Typescript etc...) as well as backend(Laravel Passport) it should be same.

检查GET/POST/PUT/PATCH双方的请求类型,即前端( Javascript/Typescript etc...) 和后端( Laravel Passport) 它应该是相同的。

回答by Mahmoud Zalt

Faced something similar before, after debugging turns out it's Postman problem and nothing related to the code!

之前遇到过类似的事情,调试后发现是邮递员问题,与代码无关!

So open your terminal and try making the same request with curl:

因此,打开您的终端并尝试使用 curl 发出相同的请求:

curl -X POST -H "Accept: application/json" -F "[email protected]" -F "password=secret" -F "firstName=Mahmoud"  -F "lastName=Zalt" ....... "http://your-domain.com/api/v1/user"

If this worked means you have to change few settings with Postman itself. Really can't remember what I did to it! But it's something as simple as changing some default headers or removing the Authorization type...

如果这有效,则意味着您必须使用 Postman 本身更改一些设置。真的不记得我对它做了什么!但它就像更改一些默认标题或删除授权类型一样简单......

回答by Robert Pounder

If it helps anyone I had this exact same problem; for some reason a combination of things fixed it.

如果它可以帮助我遇到完全相同的问题的任何人;出于某种原因,事情的组合修复了它。

  1. The obvious point was that it would return a NotFoundHttpException in RouteCollection.php line 161this was due to me not sending my "api_token" in my post request.
  2. For some reason (I don't know if this made a difference) but chaining my middleware worked instead of putting it in the Route:group I did;

    Route::group(['prefix'=>'api/v1'], function () {
        Route::post('/', 'IndexController@index')->middleware('auth:api');
    });
    
  1. 显而易见的一点是它会返回一个NotFoundHttpException in RouteCollection.php line 161这是因为我没有在我的帖子请求中发送我的“api_token”。
  2. 出于某种原因(我不知道这是否有所作为)但是链接我的中间件而不是将它放在我所做的 Route:group 中;

    Route::group(['prefix'=>'api/v1'], function () {
        Route::post('/', 'IndexController@index')->middleware('auth:api');
    });
    

回答by mopo922

This error can also be caused by a request body that's too large. In my case, I was accidentally sending an object with many sub-objects that all had many other sub-objects. Pruning my request data solved the issue.

此错误也可能由过大的请求正文引起。就我而言,我不小心发送了一个包含许多子对象的对象,这些子对象都有许多其他子对象。修剪我的请求数据解决了这个问题。

回答by Joseph El Khoury

After long hours of digging and digging, I couldn't find any solution to my problem.

经过长时间的挖掘和挖掘,我找不到任何解决问题的方法。

I had to create a new Laravel project from scratch and add everything I had in my old project. To my surprise, everything worked perfectly and I still don't understand why!

我必须从头开始创建一个新的 Laravel 项目,并添加我在旧项目中拥有的所有内容。令我惊讶的是,一切都运行良好,但我仍然不明白为什么!

Anyways, thanks to all who tried to help on this :) Cheers!

无论如何,感谢所有为此提供帮助的人:) 干杯!