【问题标题】:How to make Laravel return a View's "Content-Type" header as "application/javascript"?如何让 Laravel 将 View 的“Content-Type”标头返回为“application/javascript”?
【发布时间】:2013-09-12 04:19:05
【问题描述】:

我正在尝试使用 [script src=""] 标记从外部网站输出一个动态 javascript 文件以包含在内。由于视图使用 Blade 引擎,因此它呈现为 text/html

我希望此视图的 Content-Type 标头设置为 application/javascript,只是为了避免 Chrome 用“Resource interpreted as Script but transferred with MIME type text/html:”之类的消息骚扰我

我的控制器:

{
    // ...
    return View::make('embedded')->with('foo', $foo);
}

视图本身:

<?php
header('Content-Type: application/javascript; charset=UTF-8', true);
?>(function(jQuery) {
    // append stylesheets to <head>
    var file;
    // ...
})(jQuery);

我发现我可以在我的视图中使用header() 添加自定义标头,如预期的X-Content-Type,但是当我尝试重新定义Content-Type 标头时,即使使用replace参数设置为true

我肯定在这里遗漏了一些明显的东西,希望你能指出来:)

非常感谢您的帮助

【问题讨论】:

    标签: php laravel laravel-4


    【解决方案1】:

    Laravel 允许你通过 Response 类修改头部信息,所以你必须使用它。从您的视图中删除 header 行并在您的控制器中尝试这样:

    $contents = View::make('embedded')->with('foo', $foo);
    $response = Response::make($contents, $statusCode);
    $response->header('Content-Type', 'application/javascript');
    return $response;
    

    【讨论】:

    • 实际上,控制器是处理标题而不是视图的理想场所;)
    • 这不起作用.!!!我得到 make () not defined 我已经继承了响应。
    • @sam:它应该适用于 Laravel 4,但不适用于 Laravel 5。
    【解决方案2】:

    在 Laravel 5.4 中你可以这样做:

    $contents = view('embedded')->with('foo', $foo);
    return response($contents)->header('Content-Type', 'application/javascript');
    

    顺便说一句,不需要在视图中设置标题。

    【讨论】:

    • 当我尝试这个时,我得到“Undefined method 'header'.intelephense(1013)”
    【解决方案3】:

    在 Laravel 5.6 中:

    return response()
        ->view('embedded', ['foo' => $foo])
        ->header('Content-Type', 'application/javascript');
    

    【讨论】:

      【解决方案4】:

      如果您只是在一个变量中包含 JSON,并且您想将其发送到浏览器并在标头中设置正确的内容类型,您需要做的就是:

      return Response::json($json);
      

      显然,假设 $json 包含您的 JSON。

      根据您的具体情况,使用视图可能更有意义(而不是通过连接字符串来构建 JSON),但如果您使用视图来构建字符串,这仍然是一种选择。大致按照这些思路应该可以工作:

      $json = View::make('some_view_template_that_makes_json') -> with ('some_variable', $some_variable)
      return Response::json($json);
      

      (抱歉,如果我错过了需要更手动方法的问题的某些部分!至少这对于其他来到这里并想知道如何从 Laravel 发送具有正确内容类型集的 JSON 的人来说应该是有用的。)

      【讨论】:

        【解决方案5】:

        Response::json() 不再可用。

        你可以使用 response->json() 代替。

        use Illuminate\Contracts\Routing\ResponseFactory;
        $foobar = ['foo' => 0, 'bar' => 'baz'];
        return response()->json($foobar);
        

        给予:

        {"foo":0,"bar":"baz"}
        

        带有相应的标题。

        【讨论】:

        • 为我工作谢谢:)
        【解决方案6】:

        这对我有用 return Response::view($landing)-&gt;header('X-Frame-Options', 'DENY');

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2012-07-11
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-10-06
          • 1970-01-01
          • 2019-06-28
          • 2011-01-04
          相关资源
          最近更新 更多