skip to Main Content

I have been connecting my Laravel API backend to my NextJS frontend. Everything worked well until I put part of my NextJS app onto a subdomain and I immediately got CORS errors.

"Access to XMLHttpRequest at 'http://myapp.test:8080/dashboard' (redirected from 'http://myapp.test:8080/api/login') from origin 'http://app.myapp.test:8080' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.

http://myapp.test:8080/api/login receives data back, but when I set it to it’s normally (working when on same domain) behaviour of redirecting to the main application, it throws the error.

Any help would be appreciated.

2

Answers


  1. Hi have you tried the following method

    //AppHttpMiddleware;

    public function handle($request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', '*')
            ->header('Access-Control-Allow-Credentials', true)
            ->header('Access-Control-Allow-Headers', 'X-Requested-With,Content-Type,X-Token-Auth,Authorization')
            ->header('Accept', 'application/json');
    }
    

    check config/cors.php

    change paths array to * (‘paths’ => [‘*’])

    i hope it solves the issue

    Login or Signup to reply.
  2. As google says:

    Cross-origin resource sharing (CORS) is a standard mechanism that allows JavaScript XMLHttpRequest (XHR) calls executed in a web page to interact with resources from non-origin domains. CORS is a commonly implemented solution to the same-origin policy that is enforced by all browsers.

    Read more

    An example of a cross-origin request, JavaScript code served from
    https://domain-a.com uses ajax to make a request for https://domain-b.com/data.json

    Now browser will block that request due to security.

    Solution

    The solution is to send a header for some domains. An example of nginx:

    location / {
        add_header Access-Control-Allow-Origin *;
    }
    

    More secure option:

    location / {
        add_header Access-Control-Allow-Origin "http://app.myapp.test" always;
    }
    

    In laravel you can manually send headers or use middlewares

    $request->headers->set('Access-Control-Allow-Origin', '*');
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search