dongyilai4214 2016-01-08 10:26
浏览 42

设置HTTP请求的状态

I tried to set the http status in my custom API when a request is being made.

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");

But when I make my server request in POSTMAN, I see status 200 and not 201 as set in the code above and the message is not appearing at all. Do I need to do it differently?

I am using the Laravel framework and implemented the functions by the book "Build APIs you won't hate"

I used the http_response_code() method as suggested and set the code like this:

public function respondCreated($message) {
    $this->setStatusCode(201)->respond([
        'message' => $message
    ]);
    http_response_code(201);
    return $this;
}

When I then return the response code it shows properly, but the POSTMAN Status is still 200?

The helper method by laravel is response() and is described as:

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);
});

enter image description here

enter image description here

  • 写回答

1条回答 默认 最新

  • dongxiaoke2018 2016-01-08 10:32
    关注

    You can set the HTTP Response Code as stated on PHP documentation.

    <?php
    
    // Get the current default response code
    var_dump(http_response_code()); // int(200)
    
    // Set our response code
    http_response_code(404);
    
    // Get our new response code
    var_dump(http_response_code()); // int(404)
    ?>
    
    评论

报告相同问题?

悬赏问题

  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。