CORS error when fetching products from Laravel API using React frontend

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.

  1. 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, ];

  2. 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>

  3. Modified the index function in my Laravel Controller to allow all methods:

    php
    

    Copier le code

    public function index() { return response()->json(Produits::all()); }

  4. 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 Laravel cors.php files, but the error persists.

  • Any guidance on additional steps to troubleshoot or correct this issue would be greatly appreciated!


Additional Context

  1. Backend: Laravel 9 with Sanctum for authentication.

  2. 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!

New contributor

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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật