I have PDF files under public directory. and i can access them by visiting the link on the browser, and it works fine.
However when i try to embed the PDF doc in FranckFreiburger/vue-pdf
i get:
CORS header ‘Access-Control-Allow-Origin’ missing
here is my cors.php:
<?php return [ 'paths' => ['*'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false, ];
And here is my kernel.php:
protected $middleware = [ FruitcakeCorsHandleCors::class, ... ];
I have also tried removing the whole package and use plain php like so, but it is still not working:
bootstrap.php
<?php header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS'); header('Access-Control-Allow-Headers: Origin, Content-Type, X-Auth-Token, Authorization, Accept,charset,boundary,Content-Length'); header('Access-Control-Allow-Origin: *');
EDIT
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
The reason CORS is not working is because none of your PHP code is even being run for static files.
If you are using Apache, and look at the public/.htaccess
it contains:
# Handle Front Controller... RewriteCond %{REQUEST_FILENAME} !-d RewriteCond %{REQUEST_FILENAME} !-f RewriteRule ^ index.php [END]
If you go on Nginx, and look at the config located in /etc/nginx/sites-available
, it should contain:
location / { try_files $uri $uri/ /index.php?$query_string; }
In either case, the above basically means that if the request is not a directory or a file within public
then run the script in index.php
.
You have a few options:
Method 1: Adjust the server configs
You can make modifications to your server configs to enable CORS for certain or all static files:
Method 2: Serve the file through the application
- Move the file into somewhere in Storage
- Create a new route and controller to something like this:
Route::get('files/my-example-file.pdf', function () { return response()->file($path); });
Remember the path should be absolute like '/home/vagrant/code/my-project/storage/app/sample.pdf
Also remember to apply the CORS middle-ware to the route somehow (e.g. through a middleware group).
Now the CORS middleware should run.
Method 2
In my case i follow the link in Yahya Uddin answer for Apache Cors configuration and the only thing i need is to enable Mod_Headers with this command
a2enmod headers
and restart apache
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0