1

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

我的代码

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

根据Dingo 文档,我可以在函数中提供一个location$content作为参数created()

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

有人可以解释一下这个created()功能吗?

4

1 回答 1

2

这样做是设置Location标题,如源代码所示

/**
 * 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
于 2016-08-29T18:05:06.097 回答