fruitcake / laravel-cors

Adds CORS (Cross-Origin Resource Sharing) headers support in your Laravel application
MIT License
6.27k stars 613 forks source link

CORS issue with accessing storage folder images in Laravel 7 #502

Closed YaroslavLazarev closed 4 years ago

YaroslavLazarev commented 4 years ago

Hi!

I am using Laravel 7, I have created a symlink for my storage folder. When I trying to access any file from storage using GET request I got cors error:

_Access to XMLHttpRequest at 'http://mysite/storage/uploads/45YCw54WtL_1601382465.png' from origin 'http://mysite' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource._

My cors config:

'paths' => ['*'],

'allowed_methods' => ['*'],

'allowed_origins' => ['*'],

'allowed_origins_patterns' => [],

'allowed_headers' => ['*'],

'exposed_headers' => [],

'max_age' => 0,

'supports_credentials' => false,

I tried to set Header set Access-Control-Allow-Origin '*' in .htaccess. But it doesn't help. All API endpoints work as well.

YaroslavLazarev commented 4 years ago

Static files aren't in Laravel router

yajo10 commented 2 years ago

I stumbled above the same issue in laravel 8 and laravel 9. The issue is in the server.php file. According to this stackoverflow I modified my server.php to this:

<?php

/**
 * Laravel - A PHP Framework For Web Artisans
 *
 * @package  Laravel
 * @author   Taylor Otwell <taylor@laravel.com>
 */

$uri = urldecode(
    parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
);

// 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.
if ($uri !== '/' && file_exists(__DIR__.'/public'.$uri)) {
    /*
     * The original content from Laravel causes the php built in web-server to
     * return the file statically but without looking up the .htaccess file:
     * return false;
     */

    /*
     * We need to get the file content and set the CORS-Header. That's needed for fetching
     * resources (images) from js directly for storing them in the pouchdb in frontend.
     */
    $filePath = __DIR__.'/public'.$uri;
    header("Access-Control-Allow-Origin: *");
   //This just works for images and videos. If you need to return css and js take at a look and the following links
    $mime = mime_content_type($filePath);
    // https://stackoverflow.com/questions/45179337/mime-content-type-returning-text-plain-for-css-and-js-files-only
    // https://stackoverflow.com/questions/7236191/how-to-create-a-custom-magic-file-database
    header("Content-type: {$mime}");
    echo file_get_contents($filePath);
    return true;
}

require_once __DIR__.'/public/index.php';