Set CORS headers for static files in Laravel artisan serve


 I was working on a Laravel website and i had to call a json file via ajax. the json file is a static file placed in public folder. The ajax call did not work because of CORS. It is normal because the static files do not go through PHP and Laravel's cors will not work. 

So i did some changes in the laravel server.php file. here is the final codes;

<?php
$uri = urldecode(
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);
$publicPath = __DIR__.'/public';

// This file allows us to emulate Apache's "mod_rewrite" functionality from the
// built-in PHP web server. This provides a convenient way to test a Laravel
// application without having installed a "real" web server software here.
// Serve static files with CORS headers
if ($uri !== '/' && file_exists($publicPath.$uri)) {

// Add CORS headers for JSON files (or other file types you need)
if (preg_match('/\.(json)$/i', $uri)) {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: GET, OPTIONS');
header('Content-Type: ' . mime_content_type($publicPath . $uri));
}

// Let the built-in server handle the file serving
return readfile($publicPath . $uri);
}

require_once $publicPath . '/index.php';


You can do the same. Maybe you will have to modify something more.

Then i ran the PHP development server directly like this:

php -S localhost:8000 server.php

Now it works locally. 

The production server is different because you will normally use apache2 or nginx in the middle of network and PHP. so apache2/nginx will handle the cors for static files

Comments