Laravel-返回json和http状态码
问题描述:
如果我返回一个对象:
return Response::json([
'hello' => $value
]);
状态码将为200.如何将其更改为201,并显示一条消息并与json对象一起发送?
the status code will be 200. How can I change it to 201, with a message and send it with the json object?.
我不知道是否有一种方法可以在Laravel中设置状态代码.
I don't know if there is a way to just set the status code in Laravel.
答
You can use http_response_code()
to set HTTP response code.
如果未传递任何参数,则http_response_code将获取当前状态码.如果您传递参数,它将设置响应代码.
If you pass no parameters then http_response_code will get the current status code. If you pass a parameter it will set the response code.
http_response_code(201); // Set response status code to 201
对于Laravel(引用自: https://stackoverflow.com/a/14717895/2025923 ):>
For Laravel(Reference from: https://stackoverflow.com/a/14717895/2025923):
return Response::json([
'hello' => $value
], 201); // Status code here