Laravel 5.2 无法将跨域 jQuery 方法识别为 AJAX

Laravel 5.2 not recognizing cross-domain jQuery method as AJAX

Laravel 5.2 未将来自跨域 jQuery load() 方法的请求识别为 AJAX:

jQuery 来自站点一:

 $('#results').load('http://site2.com/test');

站点二的控制器方法:

 public function myMethod(Request $request)
    {
        header("Access-Control-Allow-Origin: *");
        header('Access-Control-Allow-Credentials: true');

        if (!$request->ajax()) {
            abort(403, 'Invalid Request');
        }
          // do something
    }

请求已收到,除了未被识别为 AJAX 请求外没有其他问题。从同一域调用的 load() 方法被识别为 AJAX。

有什么想法吗?

Laravel 的 HTTP 请求 class 扩展了 Symfony 的,它检查请求的 X-Requested-With header 是否设置为 'XMLHttpRequest'。默认情况下,此 header 不会在带有 jQuery 的 cross-domain 请求中发送,除非您禁用其 cross-domain 保护:

$.ajax({
    url: 'http://example.com/',
    crossDomain: false
});

创建一个包含 "X-Requested-With" 作为允许 header:

的 CORS 中间件文件
public function handle($request, Closure $next)
    {
        header('Access-Control-Allow-Origin: *');

        $headers = [
            'Access-Control-Allow-Methods' => 'POST, GET, OPTIONS, PUT, DELETE',
            'Access-Control-Allow-Headers' => 'X-Requested-With, Content-Type, X-Auth-Token, Origin, Authorization'
        ];

        if ($request->getMethod() == "OPTIONS") {
            return Response::make('OK', 200, $headers);
        }

        $response = $next($request);
        foreach ($headers as $key => $value)
            $response->header($key, $value);
        return $response;
    }

将 jQuery load() 方法替换为 ajax() 并在 jQuery AJAX 调用中添加 'X-Requested-With' header :

$.ajax({
     type: 'GET',
     url: 'http://site2.com/test',
     headers: {'X-Requested-With': 'XMLHttpRequest'},
     success: function (data)
        {
           //do something
        }
});