我和我的团队正在开发一个Laravel API,它与使用Apollo客户端使用GraphQL响应的Vue.js前端进行通信。
我们遇到了将缓存控制标头添加到响应中的问题。
Apollo无法缓存内容,因为响应中包含此标题:
Cache-Control: no-cache, private
在php.ini中,我们通过PHP禁用发送缓存控制头:
; Set to {nocache,private,public,} to determine HTTP caching aspects
; or leave this empty to avoid sending anti-caching headers.
; http://php.net/session.cache-limiter
session.cache_limiter =
在nginx配置中,我们找不到任何设置这些标头的内容。我检查了我们在sites / available中设置的全局nginx.conf和配置文件。
我可以将它添加到nginx配置中,但它只会添加另一个标头:
add_header Cache-Control "public";
Cache-Control: no-cache, private
Cache-Control: public
如果此标头不是来自PHP或nginx,那么它可能来自哪里? 我该如何删除或覆盖它?
答案 0 :(得分:2)
在任何中间件中都可以使用此示例
public function handle($request, Closure $next)
{
$response= $next($request);
return $response->header('X-TEST-HEADER','test header value');
}
但我不知道这可以解决您的问题
答案 1 :(得分:0)
如果您使用的是apache,可以通过添加.htaccess来实现。
Header always set Cache-Control "no-cache, public"
因此它将删除Cache-Control:private 并将标题响应设为
Cache-Control:no-cache , public
答案 2 :(得分:0)
在Laravel中,Cache-Control: no-cache, private
标头是通过以下逻辑在供应商软件包Symfony http-foundation中设置的:
/**
* Returns the calculated value of the cache-control header.
*
* This considers several other headers and calculates or modifies the
* cache-control header to a sensible, conservative value.
*
* @return string
*/
protected function computeCacheControlValue()
{
if (!$this->cacheControl) {
if ($this->has('Last-Modified') || $this->has('Expires')) {
return 'private, must-revalidate'; // allows for heuristic expiration (RFC 7234 Section 4.2.2) in the case of "Last-Modified"
}
// conservative by default
return 'no-cache, private';
}
$header = $this->getCacheControlHeader();
if (isset($this->cacheControl['public']) || isset($this->cacheControl['private'])) {
return $header;
}
// public if s-maxage is defined, private otherwise
if (!isset($this->cacheControl['s-maxage'])) {
return $header.', private';
}
return $header;
}
来源:Laravel 5.6 vendor/symfony/http-foundation/ResponseHeaderBag.php
行269-299
如OP在其comment至@ the_hasanov's answer中所述,可以通过实现中间件来覆盖标头。
php artisan make:middleware CachePolicy
编辑新的app/Http/Middleware/Cachepolicy.php
,使其显示为:
<?php
namespace App\Http\Middleware;
use Closure;
class CachePolicy
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
// return $next($request);
$response= $next($request);
return $response->header('Cache-Control','no-cache, public');
}
}
app/http/Kernel.php
以包括新的中间件:...
protected $middleware = [
...
\App\Http\Middleware\CachePolicy::class,
];
...