因此,我试图在资源中的响应中设置缓存控制标头,但它似乎不起作用。我总是在响应中的缓存控制标头中获得“ no-cache”。
我按照this laravel指南进行了以下操作:
<?php
namespace App\Http\Resources;
use Illuminate\Http\Resources\Json\JsonResource;
class RouteResource extends JsonResource
{
/**
* Transform the resource into an array.
*
* @param \Illuminate\Http\Request $request
* @return array
*/
public function toArray($request)
{
return [
'id' => $this->id,
'from' => $this->from,
'to' => $this->to,
'distance' => empty($this->distance) ? "" : $this->distance,
'duration' => empty($this->duration) ? "" : $this->duration,
'suspended' => (!empty($this->suspended_at))? true:false,
];
}
/**
* Customize the outgoing response for the resource.
*
* @param \Illuminate\Http\Request $request
* @param \Illuminate\Http\Response $response
* @return void
*/
public function withResponse($request, $response)
{
$response->header('Cache-Control', 'max-age=3600');
}
}
但是,效果也不理想。我终于可以通过执行以下操作来获取标题:
return response(RouteResource::collection($routes))->header('Cache-Control', 'max-age=3600');
但这感觉很不对劲,更像是骇客。我想知道为什么它最初无法按照文档中的描述使用我的资源,如何在响应中返回cache-control
标头?
答案 0 :(得分:0)
1。创建文件\ App \ Http \ Middleware \ NoCache.php
<?php
namespace App\Http\Middleware;
use Closure;
class NoCache
{
public function handle($request, Closure $next)
{
$response = $next($request);
$response->header('Cache-Control', 'no-cache, must-revalidate');
return $response;
}
}
2。打开\ App \ Http \ Kernel.php并添加到$ middleware(如果要全部使用)
\App\Http\Middleware\NoCache::class,
或定义要选择的键。
'nocache' => \App\Http\Middleware\NoCache::class,