Laravel 4 总是返回 HTTP 状态码 200

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16724772/
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-09-14 07:48:39  来源:igfitidea点击:

Laravel 4 always returns HTTP status code 200

phplaravellaravel-4

提问by Saravana Kumar

I have below code in error.php, which is triggered using App::abort(404, $error)in my controller. Still my response status code is 200(ok). I tried with various error codes like 400, 403

我在 error.php 中有以下代码,这是App::abort(404, $error)在我的控制器中使用触发的。我的响应状态代码仍然是 200(ok)。我尝试了各种错误代码,如 400、403

// NotFoundException handler
App::error(function(NotFoundException $e)
{
    $default_message = 'The requested resource was not found';

    return Response::json(array(
        'error' => $e->getMessage() ?: $default_message,
    ), 404);
 });

回答by knews12

For anyone still googling this problem:

对于仍在搜索此问题的任何人:

I was struggling with this problem for hours. For me the problem was caused by an issue with one of my controllers.

我在这个问题上挣扎了几个小时。对我来说,问题是由我的一个控制器的问题引起的。

Check all of your controllers and make sure there are no spaces in front of the <?phptag. The <?phptag should be the very first thing in the file. A single space in front of the <?phptag in any of your controllers that are routed as such:

检查所有控制器并确保<?php标签前没有空格。<?php标签应该是文件中的第一件事。<?php在您的任何控制器中,标签前面的单个空格是这样路由的:

Route::controller('example', 'ExampleController');

Will cause all status codes to be 200.

将导致所有状态代码为 200。

回答by fideloper

I believe, regardless, you should receive a 404 response, so there might be something else happening that's the result of code not included in your question.

我相信,无论如何,您应该收到 404 响应,因此可能会发生其他事情,这是您的问题中未包含的代码的结果。

That being said, the Exception class that is thrown for 404 is NotFoundHttpExceptionrather than NotFoundException.

话虽如此,为 404 抛出的 Exception 类NotFoundHttpException不是NotFoundException.

Since Laravel 4 uses Symfony's HttpKernal, that Exception is here.

由于 Laravel 4 使用 Symfony 的 HttpKernal,因此 Exception is here

You can see herewhere App::abort()throws NotFoundHttpExceptionwhen a 404 is triggered.

你可以看到这里那里App::abort()抛出NotFoundHttpException时,404被触发。

Therefore, your code should look like:

因此,您的代码应如下所示:

// NotFoundHttpException handler
App::error(function(\Symfony\Component\HttpKernel\Exception\NotFoundHttpException $e)
{
    $default_message = 'The requested resource was not found';

    return Response::json(array(
        'error' => $e->getMessage() ?: $default_message,
    ), 404);
 });

Important: This will only fire for a 404 status, as that's the corresponding code to NotFoundHttpException. Other status codes return other Exception classes. To capture allHTTP status error codes exceptions, type hint for HttpExceptionlike so:

重要提示:这只会针对 404 状态触发,因为这是 NotFoundHttpException 的相应代码。其他状态代码返回其他异常类。要捕获所有HTTP 状态错误代码异常,请键入HttpException 的提示,如下所示:

// HttpException handler
App::error(function(\Symfony\Component\HttpKernel\Exception\HttpException $e)
{
    return Response::json(array(
        'error' => $e->getMessage(),
    ), $e-> getStatusCode());
 });

Lastly, consider using a bit of Content Negotiation when deciding to return JSON or HTML.

最后,在决定返回 JSON 或 HTML 时,请考虑使用一些内容协商

回答by resmall

The solution didn't worked for me, so in case anyone is still looking for an answer, I thought it be best to put it here instead of creating another question.

该解决方案对我不起作用,因此如果有人仍在寻找答案,我认为最好将其放在这里而不是创建另一个问题。

After some time I had this problem too, in my app/Exceptions/Handler.phpI had:

一段时间后,我也遇到了这个问题,app/Exceptions/Handler.php我有:

    if ($e instanceof ModelNotFoundException) {
        if ($request->ajax()) {
            return response()
                ->json(['error' => ['No results']])
                ->header('status', 422);
        }
    }

This worked in my local environment, however, in the homolog environment (which reproduces the production environment, just to be clear) it didn't returned the correct status code.

这在我的本地环境中有效,但是,在同系环境(复制生产环境,只是为了清楚)它没有返回正确的状态代码。

After another look I started looking at Laravel's docs, and I changed the call to the following:

再看一遍后,我开始查看 Laravel 的文档,并将调用更改为以下内容:

    return response()
        ->json(['error' => ['No results.']], 422);

And that did the trick. Hope this can help.

这就是诀窍。希望这能有所帮助。