Я попытался установить статус http в моем пользовательском 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 и реализованы функции по книге «Build API, вы не будете ненавидеть»
я использовал метод 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);
});
И где код, который устанавливает фактический заголовок кода состояния HTTP? – deceze
hm ... ну ... как мне это установить? – sesc360
Не знаю. Что это за 'response()' и '-> json()' и whatnot doing ...!? – deceze