Jac*_*chi 3 json utf-8 laravel laravel-middleware
我想将我的API的JSON响应编码为UTF-8,但是每次我做出响应时,我都不想这样做:
return response()->json($res,200,['Content-type'=>'application/json;charset=utf-8'],JSON_UNESCAPED_UNICODE);
Run Code Online (Sandbox Code Playgroud)
因此,我考虑为所有API路由制作中间件,其handle(...)功能如下:
public function handle($request, Closure $next) {
$response = $next($request);
$response->header('Content-type','application/json; charset=utf-8');
return $next($request);
}
Run Code Online (Sandbox Code Playgroud)
问题是它不起作用Content-type,我的响应的标头仍然是,application/json而不是application/json; charset=utf-8;可能是因为该json(...)函数已经设置了Content-type标头,但我无法覆盖它。
我应该怎么做?
谢谢您的帮助。
它就在文档中,您想在中间件之后使用(以下代码是我的首要工作,应该可以使用):
<?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);
}
}
Run Code Online (Sandbox Code Playgroud)
通过以上方法,我们可以发现两个反模式:
将以下代码放在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);
}
Run Code Online (Sandbox Code Playgroud)
在基本控制器(app / Http / Controller.php)扩展的任何控制器中,您都可以使用 $this->jsonResponse($data);
他们使用雄辩的资源,或者如果还有更多的方法要使用分形,则可以使用(在Laravel中使用spatie包装器-https: //github.com/spatie/laravel-fractal)。
| 归档时间: |
|
| 查看次数: |
4067 次 |
| 最近记录: |