🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 返回 JSON In it’s simplest form, JSON data can be returned with a default 200 HTTP status code. > 在其最简单的形式中,可以使用默认的200 HTTP状态码返回JSON数据。 ~~~php $data = array('name' => 'Bob', 'age' => 40); $payload = json_encode($data); $response->getBody()->write($payload); return $response ->withHeader('Content-Type', 'application/json'); ~~~ Figure 15: Returning JSON with a 200 HTTP status code. We can also return JSON data with a custom HTTP status code. > 我们还可以使用定制的HTTP状态码返回JSON数据。 ~~~php $data = array('name' => 'Rob', 'age' => 40); $payload = json_encode($data); $response->getBody()->write($payload); return $response ->withHeader('Content-Type', 'application/json') ->withStatus(201); ~~~ Figure 16: Returning JSON with a 201 HTTP status code. **Reminder** The Response object is immutable. This method returns a*copy*of the Response object that has a new Content-Type header.**This method is destructive**, and it*replaces*the existing Content-Type header. > 提醒 > Response对象是不可变的。此方法返回具有新内容类型标头的响应对象的*copy*。**这个方法是毁灭性的**,它`替换`了现有的内容类型头。 ## Returning a Redirect返回一个重定向 You can redirect the HTTP client by using the`Location`header. > 您可以使用`Location`报头重定向HTTP客户端。 ~~~php return $response ->withHeader('Location', 'https://www.example.com') ->withStatus(302); ~~~ Figure 17: Returning a redirect to https://www.example.com