skip to Main Content

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


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

    <?php
    
    namespace AppHttpMiddleware;
    
    use Closure;
    
    class Cors
    {
        /**
         * Handle an incoming request.
         *
         * @param  IlluminateHttpRequest  $request
         * @param  Closure  $next
         * @return mixed
         */
        public function handle($request, Closure $next)
        {
            $response = $next($request);
            $response->headers->set('Access-Control-Allow-Origin' , 'http://localhost:19000');
            $response->headers->set('Access-Control-Allow-Methods', 'POST, GET, OPTIONS, PUT, DELETE');
            $response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Accept, Authorization, X-Requested-With, Application');
            return $response;
        }
    }
    

    After creating the middleware you have to define the middleware on app/Http/Kernel.php file under $routeMiddleware array like:

    protected $routeMiddleware = [
            ...(Any previous middlewares)       
    
            'cors' => AppHttpMiddlewareCors::class,
    
        ];
    

    Once you have done this you can use it in your API route groups or any individual route that you have created. For example:

    Route::middleware(['cors'])->prefix('auth')->group(function () {
        Route::post('register', [AuthController::class, 'register']);
    });
    

    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.

    Login or Signup to reply.
  2. You can install Allow CORS: Access-Control-Allow-Origin Chrome extension to solve this issue.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search