gpt4 book ai didi

json - Laravel:以 UTF-8 编码 JSON 响应

转载 作者:行者123 更新时间:2023-12-02 02:56:56 27 4
gpt4 key购买 nike

我想将 API 的 JSON 响应编码为 UTF-8,但每次我做出响应时我不想这样做:

return response()->json($res,200,['Content-type'=>'application/json;charset=utf-8'],JSON_UNESCAPED_UNICODE);

所以我考虑为所有 API 路由制作一个中间件,其 handle(...) 函数如下:

public function handle($request, Closure $next) {
$response = $next($request);
$response->header('Content-type','application/json; charset=utf-8');
return $next($request);
}

问题是它不起作用,我响应的 Content-type header 仍然是 application/json 而不是 application/json;字符集=utf-8;也许是因为 json(...) 函数已经设置了 Content-type header ,我无法覆盖它。

我该怎么办?

感谢您的帮助。

最佳答案

就在文档中,您想要使用 after 中间件(以下代码来 self 的脑海,它应该可以工作):

<?php

namespace App\Http\Middleware;

use Closure;

class AfterMiddleware
{
public function handle($request, Closure $next)
{

/** @var array $data */ // you need to return array from controller
$data = $next($request);

return response()->json($data, 200, ['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'],
JSON_UNESCAPED_UNICODE);
}
}

通过上述方法,我们可以发现两个反模式:

  • 首先,在中间件中制作响应(您应该在 Controller 中执行此操作)。

  • 此外,也许应该避免使用未转义的 JSON 响应,因为 Laravel 创建者出于某种原因默认“转义为纯文本”,但如果您的所有 Web-API客户端应用程序支持 UTF-8,然后未转义可提高性能。

    Experience shows that most clients beside supporting it, they even assume UTF-8 if charset is missing from Content-Type header.

删除中间件并仅使用 Controller

将以下代码放入app/Http/Controller.php

protected function jsonResponse($data, $code = 200)
{
return response()->json($data, $code,
['Content-Type' => 'application/json;charset=UTF-8', 'Charset' => 'utf-8'], JSON_UNESCAPED_UNICODE);
}

在任何由基本 Controller (app/Http/Controller.php) 扩展的 Controller 中,您可以使用 $this->jsonResponse($data);

专业人士如何做到这一点

他们使用 eloquent resources或者如果还有更多事情发生 fractal是要走的路(在 Laravel 中使用 spatie 包装器 - https://github.com/spatie/laravel-fractal )。

关于json - Laravel:以 UTF-8 编码 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50717005/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com