【问题标题】:Laravel 5.4 API routeLaravel 5.4 API 路由
【发布时间】:2017-06-29 17:20:36
【问题描述】:

我的网络路由正在运行,但是我无法发布到我的 api 路由,我收到了MethodNotAllowedHttpException。我认为这是一个 csrf 令牌问题,因为 GET 有效,但我不知道如何解决它。我正在使用 Postman 来模拟 api 请求。

auth.php

'guards' => [
    'web' => [
        'driver' => 'session',
        'provider' => 'users',
    ],

    'api' => [
        'driver' => 'token',
        'provider' => 'devices',
    ],
],

RouteServiceProvider.php

protected function mapApiRoutes()
{
    Route::middleware('api')
         ->namespace($this->namespace)
         ->group(base_path('routes/api.php'));
}

路由/api.php

Route::post('api', ['uses' => 'DeviceController@api']);

kernel.php

protected $middlewareGroups = [
    'web' => [
        \App\Http\Middleware\EncryptCookies::class,
        \Illuminate\Cookie\Middleware\AddQueuedCookiesToResponse::class,
        \Illuminate\Session\Middleware\StartSession::class,
        // \Illuminate\Session\Middleware\AuthenticateSession::class,
        \Illuminate\View\Middleware\ShareErrorsFromSession::class,
        \App\Http\Middleware\VerifyCsrfToken::class,
        \Illuminate\Routing\Middleware\SubstituteBindings::class,
    ],

    'api' => [
        'throttle:60,1',
        'auth:api',
        'bindings',
    ],
];

这是对旧版本 Laravel 的升级,它正在运行,我通过安装 Laravel 5.4 的新副本进行升级,然后复制我的代码,并根据需要进行更改。

【问题讨论】:

  • 您从哪里以及如何打电话?如果来自 ajax 共享该代码?
  • @detective404 我正在使用 Postman 进行通话。我正在使用 POST 请求调用 www.mydomain.com/api
  • 嘿@meeeee 你找到这个问题的解决方案了吗?我有类似的问题如果它在你身边解决了,请告诉我。
  • @DenisBhojvani 是的,我做到了。我在强制使用 https 时尝试使用 http。

标签: php post laravel-5 routes


【解决方案1】:

使用 POST 请求发送 _token 这样的值

    $.ajax({
        type: "POST",
        url: "/your url",
        data: {_token:$("input[name='_token']").val(),'other':'Other value'}
    }).done(function( response ) {
        ....
    });

【讨论】:

  • 这对我来说在使用 api 时没有意义。应该不需要令牌
  • 你在调用哪个网址?
  • 您需要在 kernel.php 中注释 \App\Http\Middleware\VerifyCsrfToken::class, 以不验证,因为您无法从邮递员发送 _token
  • 我不能这样做,因为我需要令牌来处理网站的 Web 部分。我确实尝试将 api 路由添加到 csrf 令牌 except 方法,但这没有帮助。这可能根本不是令牌问题。
  • 感谢您的帮助
【解决方案2】:

对不起,我在一个月前犯了同样的错误。问题是我没有使用https。奇怪的是我如何获得 MethodNotAllowedException,我想这让我失望了。

【讨论】:

  • Brilliant X'D 热爱诚实 :p
猜你喜欢
  • 2017-09-20
  • 2017-10-12
  • 2018-04-13
  • 1970-01-01
  • 2017-08-09
  • 2018-02-26
  • 2017-09-03
  • 2017-10-17
  • 2019-04-25
相关资源
最近更新 更多