简体   繁体   中英

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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM