Ad

Calling A PHP Lumen Backend From A React Frontend And Solving The CORS Issues

- 1 answer

So basically I have use Lumens as my backend api (at localhost:8000). Now on my frontend React app (at localhost:3000) I make requests to my backend like this:

fetch(`http://localhost:8000/feedback/add`, {
            method: 'POST',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json',
            },
            body: JSON.stringify({
                feedback: this.state.feedback,
                email: this.state.email,
            }),
        })

However I keep running into cors issues as I am making a request to/from different servers. I have been googling and trying to figure out the solutions but there seems to be so many different ideas such as using middleware in Lumens (many different solutions) or setting mode: no-cors frontend side. But I really do not know what to go with as they all seem to still cause further issues.

Has anyone a similar setup to this? And what would be the way to solve this once and for all?

Ad

Answer

I've developed a few a SPAs with Laravel as my backend. By default, Laravel protects you from unauthorized calls to your API, which sounds like what you are running into.

What I recommend you do to allow calls to your backend from third party domains, is installing the Spatie CORS package with composer:

composer require spatie/laravel-cors

This package is compatible with both Laravel and Lumen. The readme file has all the installation instructions you need.

Once installed properly, you will be able to specify which third party domains can access your API:

'allow_origins' => [

    '*', // all domains are allowed... or set them up individually:

    'https://my-site-1.com',
    'https://my-site-2.com', 
],

The Spatie CORS package: https://github.com/spatie/laravel-cors

Ad
source: stackoverflow.com
Ad