skip to Main Content

i built a website the frontend using react and the backend using laravel 10 then deployed the frontend part on vercel and the laravel api using a shared hosting
the website works fine when i make the requests using my localhost as a server but when i try using the backend server it gives me this error
Access to XMLHttpRequest at ‘https://mybackend.hstn.me/api/homePage’ from origin ‘https://easylearning-seven.vercel.app’ has been blocked by CORS policy: No ‘Access-Control-Allow-Origin’ header is present on the requested resource.

the website worked fine before the deploying but after i deployed my website it gives me error

2

Answers


  1. Add Middleware

    namespace AppHttpMiddleware;
    
    use Closure;
    use IlluminateHttpRequest;
    use SymfonyComponentHttpFoundationResponse;
    
    class Cors
    {
        /**
         * Handle an incoming request.
         *
         * @param  Closure(IlluminateHttpRequest): (SymfonyComponentHttpFoundationResponse)  $next
         */
        public function handle(Request $request, Closure $next): Response
        {
            return $next($request)
                ->header('Access-Control-Allow-Origin', '*')
                ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
                ->header('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, X-Token-Auth, Authorization');
        }
    }
    
    Login or Signup to reply.
  2. You have cors file config on config/cors.php and change :

    'allowed_origins' => ['*'],

    to

    'allowed_origins' => ['https://easylearning-seven.vercel.app'],

    and you can specify more option about header within this file

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