Joaquin Colella
Joaquin Colella

Reputation: 142

No 'Access-Control-Allow-Origin' header is present on the requested resource in Laravel Apache Project

I have two laravel projects on the same Ubuntu Apache server.

Project A is available in test.EXAMPLE.com and "Project B" in www.EXAMPLE.com. "Project A" has a website were I make AJAX requests to Project B. In each of them I have a GoDaddy SSL certificate (one for test.EXAMPLE.com and another one for www.EXAMPLE.com).

The error I get is:

XMLHttpRequest cannot load https://www.EXAMPLE.com/api_url. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://test.EXAMPLE.com' is therefore not allowed access.

How can I solve this problem?. I tried adding an .htaccess inside "Project B" with

Header set Access-Control-Allow-Origin "*"

and also adding in the "Project A" AJAX Header, this

'Access-Control-Allow-Origin' : '*',
'Access-Control-Allow-Methods' : 'GET, POST, PUT, DELETE, OPTIONS'

Whoever can help me, thank you.

Upvotes: 0

Views: 936

Answers (2)

Robert
Robert

Reputation: 5963

You can create a simple middleware for laravel:

<?php

namespace App\Http\Middleware;

use Closure;

class CorsHeaders
{
    /**
     * Append CORS headers to response
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);

        $response->header('Access-Control-Allow-Origin', '*');
        // add allowed headers if needed
        // $response->header('Access-Control-Allow-Headers', '');
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');

        return $response;
    }
}

And register it in $middleware array in the http kernel.

Upvotes: 0

Jan Wytze
Jan Wytze

Reputation: 3497

Install this package:
https://github.com/barryvdh/laravel-cors

With this package you can very easy add the cors headers to your options requests.
For some reason I do always have trouble with the cors headers. But they should just be there for every option request that is done with an ajax call.

Upvotes: 1

Related Questions