Laravel不创建响应自定义标头

时间:2020-05-07 11:24:47

标签: laravel http-headers response-headers

当请求全部为json时,我得到了我的'xxx'标头,但是当它直接请求页面时-我的标头在响应中不存在。

我尝试了response()->headerresponse('content',200,['xxx'=>'xxx'])的任何变体,但都没有成功

我在控制器中的代码:

return $request->wantsJson()
            ? response([
                'html'          => view('components.tarif-list', compact('tarifs'))->render(),
                'pagination'    => $tarifs->appends(request()->query())->links()->toHtml(),
                'head'          => $seo_block,
                'stats'         => $stats
            ])->header('xxx','xxx')
            : response(view('home',compact('tarifs','seo_block'))->render())->header('xxx','xxx');

home.blade.php

@extends('layouts.main')

@section('content')
    <x-filters/>
    <div id="head" class="alert alert-success" role="alert">
        @if(!empty($seo_block))
        {!! $seo_block !!}
            @elseif($tarifs->isEmpty())
            empty
            @else
            hello
        @endif
    </div>
    {{$tarifs->appends(request()->query())->links()}}
    <table id="tarif-list" class="table table-hover table-striped">
        <x-tarif-list :tarifs="$tarifs"/>
    </table>
    {{$tarifs->appends(request()->query())->links()}}
@endsection

2 个答案:

答案 0 :(得分:0)

如果您添加此行代码

response(view('home',compact('tarifs','seo_block'))->render())->header('xxx','xxx')

您将看到此回复

Symfony\Component\HttpFoundation\ResponseHeaderBag {#2878
  #computedCacheControl: array:2 [
    "no-cache" => true
    "private" => true
  ]
  #cookies: []
  #headerNames: array:3 [
    "cache-control" => "Cache-Control"
    "date" => "Date"
    "xxx" => "xxx"
  ]
  #headers: array:3 [
    "cache-control" => array:1 [
      0 => "no-cache, private"
    ]
    "date" => array:1 [
      0 => "Thu, 07 May 2020 11:27:31 GMT"
    ]
    "xxx" => array:1 [
      0 => "xxx"
    ]
  ]
  #cacheControl: []
}

所以键在那里,但是如何检索刀片文件中的标头?

答案 1 :(得分:0)

问题出在响应dump()之前的控制器中,众所周知,标头必须是页面上的第一内容。

但是为什么php或laravel没有告诉您。 默认的PHP警告:

PHP Warning:  Cannot modify header information - headers already sent by..........