簡體   English   中英

Laravel 5.2沒有將跨域jQuery方法識別為AJAX

[英]Laravel 5.2 not recognizing cross-domain jQuery method as AJAX

Laravel 5.2沒有從跨域jQuery load()方法中將請求識別為AJAX:

來自網站1的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 Request類擴展了Symfony,它檢查請求的X-Requested-With標頭是否設置為'XMLHttpRequest'。 除非您禁用其跨域保護,否則默認情況下不會在使用jQuery的跨域請求中發送此標頭:

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

創建一個CORS中間件文件,其中包含“X-Requested-With”作為允許的標頭:

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;
    }

用ajax()替換jQuery load()方法,並在jQuery AJAX調用中添加一個'X-Requested-With'標頭:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM