Laravel - 返回json以及http状态代码

Gal*_*van 64 php json http-status-codes laravel

如果我返回一个对象:

return Response::json([
    'hello' => $value
]);
Run Code Online (Sandbox Code Playgroud)

状态代码将是200.如何将消息更改为201,并使用json对象将其发送?

我不知道是否有办法在Laravel中设置状态代码.

Tus*_*har 99

您可以使用它http_response_code()来设置HTTP响应代码.

如果您没有传递参数,则http_response_code将获取当前状态代码.如果传递参数,它将设置响应代码.

http_response_code(201); // Set response status code to 201
Run Code Online (Sandbox Code Playgroud)

对于Laravel(参考:https://stackoverflow.com/a/14717895/2025923 ):

return Response::json([
    'hello' => $value
], 201); // Status code here
Run Code Online (Sandbox Code Playgroud)

  • 请记住,**Symfony\Component\HttpFoundation\Response**有自己的预定义常量用于http状态代码,如果你使用除此之外它会将你的状态改变为接近它的状态...即如果你想要设置状态**449**,您将始终获得状态**500** (2认同)
  • @Tushar如果我不想发送任何数据,只需200响应怎么办?是`response() - > json([],200);`在这种情况下是否合适?或者200隐含? (2认同)

Jer*_* C. 53

这就是我在Laravel 5中的表现

return Response::json(['hello' => $value],201);
Run Code Online (Sandbox Code Playgroud)

或使用辅助函数:

return response()->json(['hello' => $value], 201); 
Run Code Online (Sandbox Code Playgroud)

  • @DJC 在第一种方法上,您将能够多次使用 Response:: 加载一次。在第二种方法中,每次使用 response()-> 时都会调用该类(如果只使用一个也没有问题)。 (2认同)

小智 23

我认为将您的响应保持在单一控制之下是更好的做法,因此我找到了最官方的解决方案.

response()->json([...])
    ->setStatusCode(Response::HTTP_OK, Response::$statusTexts[Response::HTTP_OK]);
Run Code Online (Sandbox Code Playgroud)

namespace声明后添加:

use Illuminate\Http\Response;
Run Code Online (Sandbox Code Playgroud)


小智 9

有多种方式

return \Response::json(['hello' => $value], STATUS_CODE);

return response()->json(['hello' => $value], STATUS_CODE);
Run Code Online (Sandbox Code Playgroud)

其中STATUS_CODE是您要发送的HTTP状态代码.两者都是相同的.

如果你使用的是Eloquent模型,那么简单的返回也会默认自动转换为JSON,如,

return User::all();
Run Code Online (Sandbox Code Playgroud)


小智 6

laravel 7.* 您不必指定 JSON RESPONSE,因为它会自动将其转换为JSON

return response(['Message'=>'Wrong Credintals'], 400);
Run Code Online (Sandbox Code Playgroud)