Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make Laravel return a View's "Content-Type" header as "application/javascript"?

Tags:

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.

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:"

My controller:

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

The view itself:

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

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 :)

Thanks a lot for your help

like image 593
Qwindoo Avatar asked Sep 08 '13 15:09

Qwindoo


People also ask

How can you use headers in response object in laravel?

use Response; // Or possibly: use Illuminate\Http\Response; depending on your aliases used. // Add a series of headers return response($content) ->header('Content-Type', 'text/xml') ->header('X-Header-One', 'Header Value'); // Or use withHeaders to pass array of headers to be added return response($content) -> ...

Which function returns a view in laravel?

Views may also be returned using the View facade: use Illuminate\Support\Facades\View; return View::make('greeting', ['name' => 'James']); As you can see, the first argument passed to the view helper corresponds to the name of the view file in the resources/views directory.

What is the value of content type header in an HTTP response when a server returns a webpage?

In responses, a Content-Type header provides the client with the actual content type of the returned content. This header's value may be ignored, for example when browsers perform MIME sniffing; set the X-Content-Type-Options header value to nosniff to prevent this behavior.


1 Answers

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; 
like image 114
ciruvan Avatar answered Oct 11 '22 07:10

ciruvan