Laravel Apache Project中请求的资源上没有“Access-Control-Allow-Origin”标头

时间:2017-06-14 19:09:38

标签: php ajax apache laravel

我在同一个Ubuntu Apache服务器上有两个laravel项目。

项目A位于test.EXAMPLE.com,“Project B”位于www.EXAMPLE.com。 “Project A”有一个网站,我向项目B提出了AJAX请求。在每个网站中,我都有一个GoDaddy SSL证书(一个用于test.EXAMPLE.com,另一个用于www.EXAMPLE.com)。

我得到的错误是:

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.

我该如何解决这个问题?我尝试用“

”在“Project B”中添加.htaccess
Header set Access-Control-Allow-Origin "*"

并且还添加了“Project A”AJAX Header,这个

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

无论谁能帮助我,谢谢。

2 个答案:

答案 0 :(得分:0)

安装此包:
https://github.com/barryvdh/laravel-cors

使用此软件包,您可以非常轻松地将cors标头添加到您的选项请求中 出于某种原因,我总是遇到cors标题的问题。但是他们应该只为那些使用ajax调用完成的选项请求而存在。

答案 1 :(得分:0)

您可以为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;
    }
}

并在http内核的$middleware数组中注册。