felixele217 wrote a reply+100 XP
5mos ago
felixele217 liked a comment+100 XP
5mos ago
Laravel's middleware won't work because static files aren't served through the framework. Vite configuration also won't help because you're dealing with built assets. In production, you'd set the headers in the web server config, but artisan serve uses the built-in PHP server, which doesn't have config files. However, you can pass in a custom PHP router script to handle requests.
Out of curiosity, I looked into how the serve command works. There is a way to set headers for statically served files using a custom router, but it's a bit hacky. Just be warned.
The serve command selects a router script to pass to the built-in server. It first looks for a server.php file in the project root. If it doesn't exist, the default router script is used. You can copy the default server.php to the project root, then modify a part of it to serve JS files manually:
if ($uri !== '/' && file_exists($publicPath.$uri)) {
$path = $publicPath.$uri;
if (pathinfo($path, PATHINFO_EXTENSION) === 'js') {
header('Access-Control-Allow-Origin: *');
header('Content-Length: '.filesize($path));
header('Content-Type: application/javascript');
readfile($path);
return true;
}
return false;
}
Returning true means "I've handled this request", while false means "You handle it".
If you do this, you should see the Access-Control-Allow-Origin header on JS files when using the serve command.