Working on a Laravel/React vite project and I'm facing CORS issue, by looking to the laravel docs, it says generating a simple cors.php in the config dir will resolve the issue, but I sill face the problem from my frontend,
Notice that I tried the fruitcake/other package cors php solution but I can't install it due to dependency conflicts.
<?php
return [
/*
|--------------------------------------------------------------------------
| Cross-Origin Resource Sharing (CORS) Configuration
|--------------------------------------------------------------------------
|
| Here you may configure your settings for cross-origin resource sharing
| or "CORS". This determines what cross-origin operations may execute
| in web browsers. You are free to adjust these settings as needed.
|
| To learn more: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
|
*/
'paths' => ['*', 'sanctum/csrf-cookie'],
'allowed_methods' => ['*'],
'allowed_origins' => ['*'],
'allowed_origins_patterns' => [],
'allowed_headers' => ['*'],
'exposed_headers' => false,
'max_age' => 0,
'supports_credentials' => true,
];
A simple HTTP request using axios in the frontend
useEffect(() => {
const getReportList = async () => {
try {
setIsLoading(true);
const response = await API.get('admin/reports');
setReports(response.data.data);
setFilteredReports(response.data.data);
setActiveReport(response.data.data[0]);
} catch (error) {
errorManager(error);
} finally {
setIsLoading(false);
}
}
getReportList();
}, [])
My API axios instance snippet
import axios from "axios";
import {
SERVER_URL
} from "../../constants";
const API = axios.create({
baseURL: SERVER_URL[
import.meta.env.VITE_ENVIRONMENT],
timeout: 12000,
withCredentials: true
});
API.interceptors.request.use(async (config) => {
return config; //to handle later
});
API.interceptors.response.use(
function (response) {
return response; //to handle later
},
function (error) {
return error; //to handle later
}
);
export default API;
It may sound weird, but basically I just hard refresh the page and deketed the config/cors.php from the backend and re-executed the command
php artisan config:publish cors
and everything was fine!