【问题标题】:Dingo Api response->created | location and content exampleDingo Api 响应->已创建 |位置和内容示例
【发布时间】:2017-01-05 19:24:01
【问题描述】:

我正在使用 Laravel 5.2 和 Dingo API 包创建 API。创建用户时,我想用新的$user->id 返回201 响应。

我的代码

return $this->response->created();

根据Dingo documentatio,我可以在created() 函数中提供location$content 作为参数。

我的问题是,我需要在这里返回什么位置信息,我尝试将我的新用户设置为 $content,但它不起作用或者我不确定会发生什么。

谁能解释一下这个created()函数?

【问题讨论】:

    标签: rest api laravel laravel-5.2 dingo-api


    【解决方案1】:

    这样做是设置Location 标头,as seen in the source

    /**
     * Respond with a created response and associate a location if provided.
     *
     * @param null|string $location
     *
     * @return \Dingo\Api\Http\Response
     */
    public function created($location = null, $content = null)
    {
        $response = new Response($content);
        $response->setStatusCode(201);
        if (! is_null($location)) {
            $response->header('Location', $location);
        }
        return $response;
    }
    

    因此,在您的示例中,由于您正在创建新用户,因此您可以将用户个人资料页面作为位置发送,例如:

    return $this->response->created('/users/123');
    

    至于内容,正如您在函数中看到的那样,它设置了返回的内容。在您的情况下,它可能是一个带有新用户信息的 json 字符串,例如:

    return $this->response->created('/users/123', $user); // laravel should automatically json_encode the user object
    

    【讨论】:

    • 酷..谢谢。这是我想知道的。你知道无论如何我可以使用转换器来处理我想要返回的内容吗?
    • 嗯,你要在那里返回原始内容,所以理论上你可以,但我不确定具体如何。
    • @ArifulHaque 你知道如何用创建的响应返回转换器数据吗?
    猜你喜欢
    • 2017-02-24
    • 2016-03-22
    • 2018-12-08
    • 2019-10-31
    • 1970-01-01
    • 1970-01-01
    • 2016-09-28
    • 2013-03-21
    • 1970-01-01
    相关资源
    最近更新 更多