【问题标题】:how to add a location header to http response from codeigniter rest server如何将位置标头添加到来自codeigniter rest服务器的http响应
【发布时间】:2015-04-05 12:38:55
【问题描述】:

我有一个使用这个库创建的 codeigniter rest api: https://github.com/chriskacerguis/codeigniter-restserver

对于我的 POST 方法,一旦成功创建资源,我想包含一个 location 标头,其中包含一个 URI 以获取新创建/更新的资源. 我不清楚如何做到这一点。 有没有人尝试过类似的东西?

到目前为止,我只是将已创建内容的详细信息添加到响应正文中……但我最终希望将 GET url 添加为位置标头。

到目前为止,这是我的逻辑:

public function widget_post()
{
        $new_widget_data = array(
                'location'  =>$this->post('location'),
                'name'   => $this->post('name'),
                'cost'   => $this->post('cost')
                );

        // validate post data
        if (!$this->isvalidpost($new_widget_data)) {
                $this->response("Invalid data",400);
        }

        // add to database
        $res = $this->widget_model->notify_servers($new_widget_data);
        $new_widget_data['results']=$res;
        if ($res) {
                //append GET url to return value                    
                $new_widget_data['GET']=base_url()."/index.php/widgets/widget/".$new_widget_data['name'];
                $this->response($new_widget_data,201); //HTTP Created 201           
        } else {
        $this->response("Unable to process request",500); //HTTP Internal server error
        }

任何建议将不胜感激。谢谢。

【问题讨论】:

    标签: php rest http-headers codeigniter-2 codeigniter-restserver


    【解决方案1】:

    我不相信当前版本的库提供了这样做的方法。

    您可以选择将 php header() 函数与 REST_Controller 类提供的 response() 函数结合使用。

    header("位置:location/to/new/resource");

    然后调用响应函数,确保设置了 201 代码。 $this->response($new_widget_data, 201);

    通常,Location 标头会默认触发重定向,因此请确保始终设置 201 代码。

    http://php.net/manual/en/function.header.php

    【讨论】:

      【解决方案2】:

      您是否尝试过重定向('widgets?widget='.$new_widget_data['name']); 还是我没抓住重点?

      【讨论】:

      • 我认为您不太了解我的问题。我不想将请求重定向到新创建的小部件。相反,当我发送带有 201 CREATED 的响应时,我想包含一个带有 URI 的位置标头标记。这说明清楚了吗?
      猜你喜欢
      • 2015-07-19
      • 2013-09-18
      • 2016-06-04
      • 1970-01-01
      • 1970-01-01
      • 2021-02-17
      • 2016-09-01
      • 2021-12-28
      • 1970-01-01
      相关资源
      最近更新 更多