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)
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)
小智 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)