I am working on a React frontend that connects to a Laravel API backend. I am facing a CORS error when trying to fetch products using axios
. I have tried multiple approaches to resolve the issue, but none of them seem to work.
-
Configured CORS settings in Laravel: I updated the
cors.php
configuration file to allow all methods and origins:php
Copier le code
return [ 'paths' => ['api/*', 'sanctum/csrf-cookie', '/auth/*'], 'allowed_methods' => ['*'], 'allowed_origins' => ['*'], // For testing purposes; will restrict this in production 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => true, ];
-
Updated the
.htaccess
file to allow all methods:apache
Copier le code
<IfModule mod_headers.c> Header set Access-Control-Allow-Origin "*" Header set Access-Control-Allow-Methods "GET, POST, OPTIONS, DELETE, PUT" Header set Access-Control-Allow-Headers "Content-Type, Authorization" </IfModule>
-
Modified the
index
function in my Laravel Controller to allow all methods:php
Copier le code
public function index() { return response()->json(Produits::all()); }
-
Cleared caches and restarted the server multiple times to ensure changes are applied.
React Component Code:
I have added logs to check if the fetch function is called. Below is a simplified version of my React component:
javascript
Copier le code
import React, { useEffect, useState } from ‘react’; import axios from ‘axios’; const Produits = () => { const [products, setProducts] = useState([]); const [loading, setLoading] = useState(true); useEffect(() => { const fetchProducts = async () => { try { console.log(‘Calling fetchProducts’); const response = await axios.get(‘https://api.shop-e-com.com/api/products’, { headers: { “Access-Control-Allow-Headers”: “Authorization, Content-Type”, “Access-Control-Allow-Origin”: “*”, ‘Content-Type’: ‘application/json; charset=utf-8’, }, withCredentials: true, }); setProducts(response.data); } catch (error) { console.error(‘Error fetching products:’, error); } finally { setLoading(false); } }; fetchProducts(); }, []); return ( <div> {loading ? <p>Loading…</p> : <p>Products loaded.</p>} </div> ); }; export default Produits;
Error Message:
When attempting to fetch the products, I encounter the following CORS error in the browser console:
csharp
Copier le code
Access to XMLHttpRequest at ‘https://api.shop-e-com.com/api/products’ from origin ‘https://shop-e-com.com’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
What am I missing?
-
I believe I’ve correctly configured the CORS settings in both my
.htaccess
and Laravelcors.php
files, but the error persists. -
Any guidance on additional steps to troubleshoot or correct this issue would be greatly appreciated!
Additional Context
-
Backend: Laravel 9 with Sanctum for authentication.
-
Frontend: React using axios for HTTP requests.
Attempted Solutions
-
Double-checked the headers in both server and client configurations.
-
Restarted the server after each configuration change.
-
Tested different settings in the CORS configuration file.
Thank you in advance for your help!
David Baehler is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
2