Laravel不会遵守状态码 [英] Laravel won't obey status code

查看:108
本文介绍了Laravel不会遵守状态码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我只是不明白,也不知道在其他地方看什么,因为即使我在主Response类中将其设置为400,以下代码的响应状态代码也始终为200.

class Api_Controller extends Base_Controller
{

    public function __construct()
    {
          parent::__construct();

          //header("HTTP/1.0 404 Not Found"); ##> This works
          //die();

          $test = array('1' => '2');
          die(Response::json($test, 400));
    }

我想念什么?我没有使用任何扩展类,只是默认的...

更新

这是上面Response::json...的输出: http://pastebin.com/RGcinSdg

如您所见,输出具有已设置的值...但出于某种原因仍返回200

Update2

var_dump(http_response_code());的输出始终为200

Update3-临时修复

我已经激活了Response::json的扩展版本,并在其中添加了以下行

http_response_code($status);

但是我还是很想知道为什么它不这样做,应该怎么做

解决方案

您无法返回控制器构造函数的响应-恰恰与Laravel中请求生命周期的流程不符.

有两种方法可以做到这一点.您可以:

a)设置一个响应过滤器,以处理您要实现的任何功能,或者 b)强制控制器ACTION返回响应.可以这样做:

class Api_Controller extends Base_Controller
{
    public $restful = true;

    public function get_index()
    {
        return Response::json($test, 400);
    }
}

它确实起作用-您只是做错了:)

I just can't understand, and don't know where else to look, as the response status code of the following code is always 200, even if I set it to 400 in the main Response class.

class Api_Controller extends Base_Controller
{

    public function __construct()
    {
          parent::__construct();

          //header("HTTP/1.0 404 Not Found"); ##> This works
          //die();

          $test = array('1' => '2');
          die(Response::json($test, 400));
    }

What am I missing? I'm not using any extended class, just the default...

Update

This is the output of the Response::json... above: http://pastebin.com/RGcinSdg

As you can see, the output has the values that has been set... but still for some reason, returns 200

Update2

The output of var_dump(http_response_code()); is always 200

Update3 - Temporary fix

I have activated an extended version of Response::json and add the following line to it

http_response_code($status);

But I would still much like to know why doesn't it does it, the way it should

解决方案

You can't return responses from controller constructors - it just doesn't fit with the flow of the request lifecycle in Laravel.

There's two ways to do this. You can either:

a) Setup a response filter that handles whatever functionality it is you're trying to achieve or b) Force a controller ACTION to return a response. This would be done like so:

class Api_Controller extends Base_Controller
{
    public $restful = true;

    public function get_index()
    {
        return Response::json($test, 400);
    }
}

It DOES work - you're just doing it incorrectly :)

这篇关于Laravel不会遵守状态码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆