簡體   English   中英

Laravel - 返回 json 和 http 狀態碼

[英]Laravel - Return json along with http status code

如果我返回一個對象:

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

狀態代碼將為 200。如何將其更改為 201,並帶有消息並與 json 對象一起發送?。

我不知道有沒有辦法在 Laravel 中設置狀態碼。

您可以使用http_response_code()設置 HTTP 響應代碼。

如果不傳遞任何參數,則 http_response_code 將獲取當前狀態代碼。 如果您傳遞參數,它將設置響應代碼。

http_response_code(201); // Set response status code to 201

對於 Laravel(參考自: https ://stackoverflow.com/a/14717895/2025923):

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

這就是我在 Laravel 5 中的做法

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

或者使用輔助函數:

return response()->json(['hello' => $value], 201); 

我認為最好的做法是將您的響應保持在單一控制下,因此我找到了最官方的解決方案。

response()->json([...])
    ->setStatusCode(Response::HTTP_OK, Response::$statusTexts[Response::HTTP_OK]);

namespace聲明之后添加:

use Illuminate\Http\Response;

有多種方式

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

return response()->json(['hello' => $value], STATUS_CODE);

其中 STATUS_CODE 是您要發送的 HTTP 狀態代碼。 兩者是相同的。

如果您使用的是 Eloquent 模型,那么默認情況下,簡單返回也將自動轉換為 JSON ,例如,

return User::all();

laravel 7.* 您不必指定 JSON RESPONSE因為它會自動將其轉換為JSON

return response(['Message'=>'Wrong Credintals'], 400);
return response(['title' => trans('web.errors.duplicate_title')], 422); //Unprocessable Entity

希望我的回答有幫助。

最好使用輔助函數而不是Facades 來完成 此解決方案從Laravel 5.7 開始運行良好

//import dependency
use Illuminate\Http\Response;

//snippet
return \response()->json([
   'status' => '403',//sample entry
   'message' => 'ACCOUNT ACTION HAS BEEN DISABLED',//sample message
], Response::HTTP_FORBIDDEN);//Illuminate\Http\Response sets appropriate headers

我自己更喜歡響應助手:

    return response()->json(['message' => 'Yup. This request succeeded.'], 200);
return response('Your text.', 422);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM