我尝试在发出请求时在自定义API中设置http状态。
protected $statusCode = 200;
public function setStatusCode($statusCode) {
$this->statusCode = $statusCode;
return $this;
}
public function respond($data, $headers = []) {
return response()->json($data, $this->getStatusCode(), $headers);
}
public function respondCreated($message) {
return $this->setStatusCode(201)->respond([
'message' => $message
]);
}
$this->respondCreated("Incident was created");
但是当我在POSTMAN中发出服务器请求时,我看到上面代码中设置的状态200而不是201,并且消息根本没有出现。我需要以不同的方式做吗?
我正在使用Laravel框架并通过本书实现了这些功能"构建您赢得并不厌恶的API#34;
我按照建议使用http_response_code()
方法,并设置如下代码:
public function respondCreated($message) {
$this->setStatusCode(201)->respond([
'message' => $message
]);
http_response_code(201);
return $this;
}
当我返回它正确显示的响应代码时,但POSTMAN状态仍为200?
laravel的辅助方法是response()
,描述为:
Returning a full Response instance allows you to customize the response's HTTP status code and headers. A Response instance inherits from the Symfony\Component\HttpFoundation\Response class, providing a variety of methods for building HTTP responses:
use Illuminate\Http\Response;
Route::get('home', function () {
return (new Response($content, $status))
->header('Content-Type', $value);
});
For convenience, you may also use the response helper:
Route::get('home', function () {
return response($content, $status)
->header('Content-Type', $value);
});