I’m encountering a CORS (Cross-Origin Resource Sharing) issue when attempting to make a GET request from my React app to a Laravel API. The specific error I’m getting in the console is as follows:
Access to XMLHttpRequest at ‘https://0748-102-146-2-29.ngrok-free.app/api/products-api’ from origin ‘http://localhost:19000’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.
Here are the relevant details of my setup:
Laravel API Configuration (config/cors.php):
return [
'paths' => ['api/*', 'http://localhost:19000', 'sanctum/csrf-cookie'],
'allowed_methods' => ['GET', 'POST', 'PUT', 'DELETE'], // Add other methods as needed
'allowed_origins' => ['*'],
'allowed_headers' => ['*'],
// ...
];
React App (useProductFetch.js):
import { useState, useEffect } from "react";
import axios from "axios";
const fetchData = async () => {
setIsLoading(true);
try {
const response = await axios.get(
"https://0748-102-146-2-29.ngrok-
free.app/api/products-api"
);
console.log("Axios request successful");
export default useProductFetch;
Postman Request:
When I send a GET request to the API endpoint https://0748-102-146-2-29.ngrok-free.app/api/products-api using Postman, I receive the expected response:
{
"data": [
// ...
]
}
Issue:
Despite configuring CORS on the Laravel API to allow all origins and methods, I’m still facing CORS issues when making requests from my React app. I’ve also verified that the server is returning the expected response when accessed directly through Postman. like so "https://0748-102-146-2-29.ngrok-free.app/api/products-api"
Question:
What could be causing this CORS issue despite having the correct CORS configuration on my Laravel API? Is there something else I need to consider or any additional steps I should take to ensure that my React app can successfully make requests to the API? Any insights or solutions would be greatly appreciated. Thank you!
2
Answers
I faced the same while working on many projects of my own. You have to create a middleware to solve this issue. The below code is the middleware that I have been using. I’ve added your localhost URL in it.
After creating the middleware you have to define the middleware on app/Http/Kernel.php file under $routeMiddleware array like:
Once you have done this you can use it in your API route groups or any individual route that you have created. For example:
Make sure to run php artisan config:clear command just to make sure there isn’t any cached config for your application.
Hope this helps.
You can install Allow CORS: Access-Control-Allow-Origin Chrome extension to solve this issue.