Resolving Cross-Origin Resource Sharing (CORS) when connecting React frontend to PHP Lumen backend

Hey folks, I’m in a bit of a pickle here. I’ve got a React app running on localhost:3000 that needs to talk to my Lumen API on localhost:8000. I’m trying to send POST requests, but I keep hitting CORS errors. It’s driving me nuts!

Here’s a snippet of what I’m trying to do:

axios.post('http://localhost:8000/api/submit-data', {
  username: this.state.username,
  message: this.state.message
})
.then(response => {
  console.log('Data sent successfully');
})
.catch(error => {
  console.error('Error:', error);
});

I’ve been googling like crazy, but there are so many different solutions out there. Some say to use middleware in Lumen, others suggest tweaking the frontend. I’m lost!

Has anyone dealt with this before? What’s the best way to fix these CORS issues once and for all? Any help would be awesome!

I’ve encountered similar CORS issues in my projects. While frontend solutions like proxies can work, I prefer handling CORS on the backend for more control. In your Lumen API, you can add the necessary headers to your responses. Here’s what I’ve found effective:

In your bootstrap/app.php, add these lines:

$app->middleware([
App\Http\Middleware\CorsMiddleware::class
]);

Then create a new middleware file CorsMiddleware.php in app/Http/Middleware with:

public function handle($request, Closure $next)
{
$response = $next($request);
$response->header(‘Access-Control-Allow-Origin’, ‘*’);
$response->header(‘Access-Control-Allow-Methods’, ‘GET, POST, PUT, DELETE, OPTIONS’);
$response->header(‘Access-Control-Allow-Headers’, ‘Content-Type, Authorization’);
return $response;
}

This approach has consistently resolved CORS issues for me across various projects.

yo, i feel ur pain! CORS can be a real headache. have u tried adding CORS middleware to ur Lumen app? in bootstrap/app.php, add this line:

$app->middleware([
// …
\Fruitcake\Cors\HandleCors::class,
]);

then install the fruitcake/laravel-cors package. that should do the trick!

hey there! cors can be tricky, right? tried using a proxy in your react app? add in package.json:

‘proxy’: ‘http://localhost:8000

and then use ‘/api/submit-data’. could that solve it? what do u think?