Getting CORS error on file upload (probably related to BrowserSync)

Hello forum!

I’m using Livewire v1.3.3.
I’m developing with Mix which uses BrowserSync and I have the setting mix.browserSync('http://project.loc'); in my webpack.mix.js file. So the URL from which I’m trying to upload is localhost:3000.
When uploading an image with the Livewire’s WithFileUploads trait enabled, I’m getting CORS error when I select a file:
Reason: header ‘x-csrf-token’ is not allowed according to header ‘Access-Control-Allow-Headers’ from CORS preflight response
The request is going to http://project.loc/livewire/upload-file?expires… instead of localhost:3000/livewire/upload-file?expires… maybe this is also a problem?
My .env file has APP_URL=http://project.loc. Changing this to http://localhost:3000 doesn’t make any difference.

I’ve shortened the class bellow so as to make it more readable.
The function startUpload() here is copied from the trait and the temporary link is dumped. At this point I get the correct url when I try to upload a file. But if I remove the dd() the upload posts to the wrong url.

class FileUploadComponent extends Component
{
    use WithFileUploads;

    public $photo;

    public function updatedPhoto()
    {
        $this->validate([
            'photo' => 'image|max:24',
        ]);
    }

    public function startUpload($name, $fileInfo, $isMultiple)
    {
        $link = URL::temporarySignedRoute(
            'livewire.upload-file', now()->addMinutes(5)
        );

        dd($link);

        $this->emitSelf('upload:generatedSignedUrl', $name, $link);
    }
}

I guess when emitting the event upload:generatedSignedUrl to UploadManager.js the link somehow gets updated.

Maybe I’m missing something in Livewire config? Any help would be appreciated, thank you!

Hi,

It is a Browsersync issue, I had the same problem and found this solution for Browsersync with Inertia but works for Livewire too!

Basically there are three steps:

1 - Stop the browser auto opening (not needed just makes thing less annoying) e.g:

mix.browserSync({
proxy: ‘localhost:8001’,
open: false,
});

2 - Add this to the top of you main layout (or layout files) e.g. in app.blade.php:

@if (app()->isLocal()) @endif

3 - No just go to your normal url not the browsersync url…in my case:

http://localhost:8001

You dont want this in production hence the @if (app()->isLocal())

Credit Warrick Bayman - https://warrickbayman.medium.com/browsersync-and-inertia-8e3ed647669a

VP

1 Like