2

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

对于我的 POST 方法,一旦成功创建资源,我想包含一个包含 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
        }

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

4

2 回答 2

2

我不相信当前版本的库提供了一种方法来做到这一点。

一种选择是将 php header() 函数与 REST_Controller 类提供的 response() 函数结合使用。

header("位置:位置/到/新/资源");

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

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

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

于 2015-02-25T15:06:41.553 回答
0

你试过重定向('widgets?widget='.$new_widget_data['name']); 还是我错过了重点?

于 2015-02-06T11:47:21.470 回答