【问题标题】:Laravel not creating response custom headerLaravel 未创建响应自定义标头
【发布时间】:2020-08-22 16:16:11
【问题描述】:

当请求是 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

【问题讨论】:

  • 我看不到任何代码,您正在检索响应标头?
  • 为什么我需要检索它?我在 http 响应头中等待它
  • 您需要以某种方式确保它是从控制器中检索到的,因此您需要将其转储到刀片文件中或在浏览器标头响应中查看。
  • 嗯.. 我不知道如何将它转储到刀片中
  • \request()->headers->get('xxx')

标签: laravel http-headers response-headers


【解决方案1】:

如果你dd这行代码

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: []
}

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

【讨论】:

  • 我没有在刀片中检索它。
  • 是的,我在 dd 中看到了标题,但为什么我无法得到响应?
  • 您在哪里使用该响应?你能分享你的代码吗?
  • 你的意思是刀片模板?
【解决方案2】:

问题出在控制器中,然后响应为dump(),并且我们知道标题必须是页面上的第一个内容。

但是为什么 php 或 laravel 不告诉它。 它的默认php警告:

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

【讨论】:

    猜你喜欢
    • 2020-04-10
    • 1970-01-01
    • 1970-01-01
    • 2014-07-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-08
    • 1970-01-01
    相关资源
    最近更新 更多