0

I'm facing a CORS (Cross-Origin Resource Sharing) problem while attempting to authenticate users from my Vue frontend to my Laravel backend, and subsequently, a Flutter mobile app. The backend API works seamlessly via Postman, and the Flutter app operates without any CORS issues. However, when attempting to log in from the Vue frontend, I encounter the following error:

Access to XMLHttpRequest at 'https://backend-api-url/login' from origin 'https://vue-frontend-url' 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.

Previously, when hosted on cPanel with Apache, this setup functioned correctly, but after migrating to Plesk with Nginx, I encounter these CORS conflicts.

Here's a summary of the setup:

  • Laravel backend API
  • Vue frontend for an admin panel
  • Flutter mobile app
  • Previous successful functionality with cPanel and Apache
  • Current issues with Plesk and Nginx

Steps taken so far:

  • Verified the backend API works with Postman
  • Checked Flutter app's functionality without CORS issues
  • Explored potential CORS configurations in Laravel and Vue

I've reviewed various solutions involving CORS headers in Laravel, Nginx configurations, and Vue Axios settings but haven't found a resolution yet. Any insights or guidance on resolving this CORS conflict specifically within the Plesk and Nginx environment would be greatly appreciated.

Thank you for your help!

1 Answer 1

0

You can create middleware called corsHandler:

    class corsHandler
{
    /**
     * Handle an incoming request.
     *
     * @param \Illuminate\Http\Request $request
     * @param \Closure(\Illuminate\Http\Request): (\Illuminate\Http\Response|\Illuminate\Http\RedirectResponse) $next
     * @return \Illuminate\Http\Response|\Illuminate\Http\RedirectResponse
     */
    public function handle(Request $request, Closure $next)
    {
        return $next($request)
            ->header('Access-Control-Allow-Origin', '*')
            ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, PATCH, DELETE, OPTIONS')
            ->header('Access-Control-Allow-Headers', '*');

    }
}

and in your kernel.php:

protected $middleware = [
...,
\App\Http\Middleware\corsHandler::class
]

and:

protected $routeMiddleware = [
...,
'cors' => \App\Http\Middleware\corsHandler::class
]
Sign up to request clarification or add additional context in comments.

3 Comments

But why did this happen in the first place?
I already used it and it didn't help, thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.