Laravel:以UTF-8编码JSON响应 [英] Laravel: Encode JSON responses in UTF-8

查看:542
本文介绍了Laravel:以UTF-8编码JSON响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to encode the JSON responses of my API to UTF-8, but every time I make a response I don't want to do this:

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

所以我考虑为所有API路由制作一个中间件,而handle(...)函数将是这样:

So I thought about making a middleware for all API routes which handle(...) function would be this:

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

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

The problem is that it doesn't work, the Content-type header of my responses is still application/json and not application/json; charset=utf-8; maybe because the json(...) function already sets a Content-type header and I cannot override it.

我应该怎么办?

谢谢您的帮助.

推荐答案

它就在文档中,您想在之后使用中间件(以下代码是我的首要选择,应该可以使用) ):

Its right there in the documentation, you want to use after middleware (following code is from top of my head and it should work):

<?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);
    }
}

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

With above approach we can spot two anti-patterns:

  • 设计中间件中的响应(您应该在 controller 中执行)
  • 使用未转义的JSON响应,Laravel的创建者将转义的默认值设为默认值,为什么要更改它呢?!
  • crafting response in middleware (you should do it in controller)
  • using unescaped JSON response, Laravel creators made default the escaped one so why change it?!

将以下代码放入 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);
}

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

in any of the controllers that are extended by base controller (app/Http/Controller.php) you can use $this->jsonResponse($data);

他们使用大量资源,或者如果

They use eloquent resources or if there is more going on fractal is the way to go (in Laravel use spatie wrapper - https://github.com/spatie/laravel-fractal).

这篇关于Laravel:以UTF-8编码JSON响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆