【问题标题】:Only Allow content type json on POST requests in laravel在 laravel 的 POST 请求中只允许内容类型为 json
【发布时间】:2020-08-23 00:15:35
【问题描述】:

我正在构建一个 laravel API,我需要能够在发布数据时只接受“应用程序/json”类型的请求。任何其他内容类型应返回 406“不可接受”响应。

我知道我可以放入一些中间件来检查这一点,但是我想知道是否有更好的方法可以实现这一点?

谢谢

【问题讨论】:

  • 中间件似乎是过滤请求类型的最佳选择
  • 有没有办法我只能在发布请求上强制执行此操作,而无需专门将中间件添加到每个发布路由?
  • 当然,我会发布答案

标签: json laravel api


【解决方案1】:

使用这个中间件:

class WeWantJsonMiddleware
{
    /**
     * We only accept json
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        if (!$request->isMethod('post')) return $next($request);


        $acceptHeader = $request->header('Accept');
        if ($acceptHeader != 'application/json') {
            return response()->json([], 406);
        }

        return $next($request);
    }
}

(修改https://stackoverflow.com/a/44453966/2311074

并将其添加到 App\Http\Kernel$middleware 以检查每个发布请求。如果您只想检查 API 帖子请求,只需将其放入 $middlewareGroups['api']

【讨论】:

  • 感谢您的回答,如果所有发布路由都在路由文件中,这很好,但我有一个结构已经与路由的多个前缀分组,所以如果我添加这个中间件我必须专门将此中间件添加到每个发布路线。据我所知,所有发布路线都需要这项检查,有没有办法可以在全球范围内应用它?
  • @SamBremner 抱歉,我误读了您的评论,您想将其应用于所有 post 路线吗?这也是可能的让我快速改变我的答案
  • @SamBremner 我现在更新了我的答案
  • 完美,正是我所需要的。谢谢:)
  • @SamBremner 感谢您的检查 :) 我现在得到 10.000 分 woho
【解决方案2】:

这是我的两分钱:

class JsonMiddleware
{
    /**
     * Accept JSON only
     *
     * @param Request $request
     * @param Closure $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $header = $request->header('Accept');
        if ($header != 'application/json') {
            return response(['message' => 'Only JSON requests are allowed'], 406);
        }

        if (!$request->isMethod('post')) return $next($request);

        $header = $request->header('Content-type');
        if (!Str::contains($header, 'application/json')) {
            return response(['message' => 'Only JSON requests are allowed'], 406);
        }

        return $next($request);
    }
}

【讨论】:

    【解决方案3】:

    像这样简单使用中间件:

    class OnlyAcceptJsonMiddleware
    {
        /**
         * We only accept json
         *
         * @param  \Illuminate\Http\Request  $request
         * @param  \Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
           // Verify if POST request is JSON
            if ($request->isMethod('post') && !$request->expectsJson()) {
                return response(['message' => 'Only JSON requests are allowed'], 406);
            }
    
            return $next($request);
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-06-28
      • 2015-09-07
      • 2015-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-21
      • 2017-03-15
      • 1970-01-01
      相关资源
      最近更新 更多