Специальные символы, генерирующие JSON с Laravel - PullRequest
0 голосов
/ 24 октября 2018

Я пытаюсь создать API в laravel.Однако, когда он генерирует json, он включает в себя эти специальные символы:

image Я вообще ничего не пытался вернуть, и он все равно возвращает мне эти символы.Я попытался поместить его во все возможные варианты кодификации, и он всегда один и тот же.

Маршруты определены в api.php :

Route::get('/draws',[
    'middleware' => 'cors',
    'uses' => 'DrawController@getDraws'
]);

Функция Controllerэто:

    public function getDraws(){
    $draws = Draw::all();
    $response = [
        'draws' => $draws
    ];

    $headers = ['Content-Type' => 'application/json; charset=UTF-8'];

    return response()->json($response, 200, $headers);
}

Мой класс Cors это:

use Closure;

class Cors {

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

    header("Access-Control-Allow-Origin: *");

    // ALLOW OPTIONS METHOD
    $headers = [
        'Access-Control-Allow-Methods'=> 'POST, GET, OPTIONS, PUT, DELETE',
        'Access-Control-Allow-Headers'=> 'Content-Type, X-Auth-Token, Origin'  
    ];
    if($request->getMethod() == "OPTIONS") {
        // The client-side application can set only headers allowed in Access-Control-Allow-Headers
        return Response::make('OK', 200, $headers);
    }

    $response = $next($request);
    foreach($headers as $key => $value)
        $response->header($key, $value);
    return $response;
}

}

ДД ($ response) возвращает мне это:

array:1 [▼
  "draws" => Collection {#236 ▼
    #items: array:8 [▼
      0 => Draw {#237 ▼
        #connection: "mysql"
        #table: null
        #primaryKey: "id"
        #keyType: "int"
        +incrementing: true
        #with: []
        #withCount: []
        #perPage: 15
        +exists: true
        +wasRecentlyCreated: false
        #attributes: array:4 [▶]
        #original: array:4 [▶]
        #changes: []
        #casts: []
        #dates: []
        #dateFormat: null
        #appends: []
        #dispatchesEvents: []
        #observables: []
        #relations: []
        #touches: []
        +timestamps: true
        #hidden: []
        #visible: []
        #fillable: []
        #guarded: array:1 [▶]
      }
      1 => Draw {#238 ▶}
      2 => Draw {#239 ▶}
      3 => Draw {#240 ▶}
      4 => Draw {#241 ▶}
      5 => Draw {#242 ▶}
      6 => Draw {#243 ▶}
      7 => Draw {#244 ▶}
    ]
  }
]

1 Ответ

0 голосов
/ 24 октября 2018

В этом нет необходимости:

$draws = Draw::all();
$response = [
    'draws' => $draws
];

$headers = ['Content-Type' => 'application/json; charset=UTF-8'];

return response()->json($response, 200, $headers);

Вы можете просто вернуть коллекцию, которая автоматически преобразуется в правильный ответ json, попробуйте сделать так:

return Draw::all()
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...