2017-07-08 255 views
2

我嘗試使用Laravel(作爲後端)和angularjs(作爲前端)構建一個簡單的api base應用程序。 在開始的時候,我遇到這個錯誤:CORS在共享主機上正常工作,但不在本地主機上

XMLHttpRequest cannot load http://127.0.0.1:8000/api/myroute . Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin ' http://localhost ' is therefore not allowed access.

  • http://127.0.0.1:8000/api/myroute是我的路線得到一些數據,在Laravel定義爲POST路線。

這雖然我已經添加了CORS中間件在我的路線(根據this sample)以這樣的方式 一個Cors中間件:

public function handle($request, Closure $next) 
    { 
     return $next($request) 
      ->header('Access-Control-Allow-Origin', '*') 
      ->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS') 
      ->header('Access-Control-Allow-Headers', 'x-requested-with, Content-Type, origin, authorization, accept, client-security-token'); 
    } 

和下面的代碼是我$http代碼,我送請求Angularjs:

$http({ 
    method: 'POST', 
    url: 'http://127.0.0.1:8000/api/myroute', 
    headers: { 
     'Content-Type': 'application/json' 
    } 
}).then(function (response) { 
    console.log(response); 
}, function (reject) { 
    console.log(reject); 
}); 

我應該補充這一點,當我上傳我的項目的主機上,這一個Cors工作好吧! 我的問題只是http://localhost

我也試過在Firefox但結果是一樣的,只是Firefox沒有顯示交叉原點錯誤,這是唯一的區別。

在這段時間,我無法在主機上開發我的項目,我需要在本地工作。 所以我需要幫助!

+0

奇怪的是你看到一個帶有環回IP的URL,但原來是本地主機。你嘗試過嗎?url:'http:// localhost:8000/api/myroute','? –

+1

當我在本地開發(我在Windows上)時使用的另一項解決方法是將FQDN添加到我的主機文件中。該行看起來像這個'dev.somesite.local 127.0.0.1',然後我可以使用'url:'http://dev.somesite.local/api/myroute' –

+0

感謝您的意見,關於第一,是的!我嘗試了兩種,他們之間沒有區別。關於第二條評論,我也是這樣做的,但它與本地主機相同或127.0.0.1 –

回答

1

嘗試下面的代碼作爲頭添加到您的laravel的index.php文件:

header('Access-Control-Allow-Origin: *'); 
header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS'); 
header('Access-Control-Allow-Headers: Origin, Content-Type, Authorization'); 

但要小心交叉origion!

相關問題