繁体   English   中英

在laravel中的json响应中获取HTTP代码

[英]get HTTP code in json response in laravel

我需要保存通过json发送的响应代码,例如404:

Route::fallback(function(){
    return response()->json(['message' => 'Not Found'], 404);
})->name('api.fallback.404');

我尝试使用以下代码:

use Illuminate\Http\JsonResponse as Resp;

if (!$this->response_code) {
     $this->response_code = Resp::getStatusCode();
}

但laravel返回此错误:

非静态方法Symfony \\ Component \\ HttpFoundation \\ Response :: getStatusCode()不应静态调用

您正在尝试从Class本身调用非静态方法(即属于该对象的方法)。 尝试这个:

use Illuminate\Http\JsonResponse as Resp;

if (!$this->response_code) {
  $this->response_code = $this->getStatusCode();
}

Jaime的回答作为解决所有错误的通用解决方案看起来不错,因为他们说无法静态调用它,但是我根本看不到Illuminate\\Http\\JsonResponse对象上的该方法-因此,您报告了500个错误。

有关JsonResponse的Laravel文档指出,您可以在JsonResponse对象上调用status()以获取响应代码的int值。

您可以使用http_response_code()获取响应代码。

$this->response_code = http_response_code;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM