如何让 Laravel 返回视图的“Content-Type"?标头为“应用程序/javascript"?

2022-01-08 00:00:00 php laravel laravel-4

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

I'm trying to output a dynamic javascript file for inclusion from external websites with the [script src=""] tag. As the view is using the Blade engine, it's rendered as text/html.

我希望该视图的 Content-Type 标头设置为 application/javascript 只是为了避免 Chrome 用类似Resource解释为脚本,但使用 MIME 类型 text/html 传输:"

I'd like the Content-Type header to be set to application/javascript for this view only to avoid Chrome bugging me with messages like "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,它似乎也没有做任何事情.

I've found that I can use header() in my view to add custom headers like X-Content-Type as expected, however when I try to redefine the Content-Type header it doesn't seem to do anything even with the replace parameter set as true.

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

I'm surely missing something obvious here, would appreciate your pointing it out to me :)

非常感谢您的帮助

推荐答案

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

Laravel lets you modify header information via the Response class, so you have to make use of it. Remove the header line from your view and try it like this in your controller:

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

相关文章