2013-11-04 31 views
6

我在做一個AngularJS項目,現在在http://localhost,laravel後端在http://api.localhost,都由nginx服務器提供服務。Laravel + AngularJS CORS不工作

製造$ http.post請求時,首先角度使得CORS OPTIONS調用,我已經配置了我的nginx服務器與適當的響應頭:

location/{ 
      add_header "Access-Control-Allow-Origin" "*"; 
      add_header "Access-Control-Allow-Credentials" "true"; 
      add_header "Access-Control-Allow-Methods" "GET,POST,DELETE,PUT,OPTIONS"; 
      add_header "Access-Control-Allow-Headers" "Keep-Alive,User-Agent,If-Modified-Since,Cache-Control,Content-Type,Authorization"; 
      add_header "Access-Control-Max-Age" "1728000"; 

      if ($request_method = 'OPTIONS') { 
        return 204; 
      } 


      #try_files $uri $uri/ /index.html; 
      try_files $uri /index.php?$query_string; 
    } 

    location = /index.php { 

      add_header "Access-Control-Allow-Origin" "*"; 
      add_header "Access-Control-Allow-Credentials" "true"; 
      add_header "Access-Control-Allow-Methods" "GET,POST,DELETE,PUT,OPTIONS"; 
      add_header "Access-Control-Allow-Headers" "Keep-Alive,User-Agent,If-Modified-Since,Cache-Control,Content-Type,Authorization"; 
      add_header "Access-Control-Max-Age" "1728000"; 

      if ($request_method = 'OPTIONS') { 
        return 204; 
      } 

      ... 
    } 

我的角模塊,還配置有:

.config(['$httpProvider', function($httpProvider) { 
    $httpProvider.defaults.useXDomain = true; 
    delete $httpProvider.defaults.headers.common['X-Requested-With']; 
}]) 

選項調用返回預期:

Access-Control-Allow-Credentials:true 
Access-Control-Allow-Headers:Keep-Alive,User-Agent,If-Modified-Since,Cache-Control,Content-Type,Authorization 
Access-Control-Allow-Methods:GET,POST,DELETE,PUT,OPTIONS 
Access-Control-Allow-Origin:* 
Access-Control-Max-Age:1728000 
Connection:keep-alive 
Date:Mon, 04 Nov 2013 02:14:16 GMT 
Server:nginx/1.2.6 (Ubuntu) 

而T3他隨後的後呼叫我做失敗的取消了身份和角度拋出一個錯誤的JS控制檯:

`XMLHttpRequest cannot load http://api.localhost/users/accesstokens. Origin http://localhost is not allowed by Access-Control-Allow-Origin.` 

我昨晚熬夜,得到了這個工作,但是當我今天又試了一次,這是回到一個方。最糟糕的問題!

什麼?

編輯:我發現了這個問題,但我仍然不明白。我查看了我的nginx訪問日誌,並且看到POST請求實際上正在觸碰服務器,即使狀態爲CANCELED。我也看到答覆是401,在得到我的請求後,答案是201.仍然是相同的CANCELED狀態。但是當我將狀態調整到200時,瞧!請求按預期工作。

AngularJS在一個跨域請求中只接受一個200狀態是否有道理?

+0

版本的nginx? – alfonsodev

+0

同樣的問題在這裏 – pajooh

回答

0

Angular.js $ http服務認爲有效的任何狀態在200和299之間,您可以在$ http源代碼中看到它; herehere我無法在其他地方找到硬編碼狀態200。

儘管Chrome的控制檯消息,問題可能是某種阿利斯泰爾·羅賓遜points in this post 檢查您的nginx被更新到最新的穩定版本,然後檢查是否正在發送「內容長度」正確頭,如果不是,我將使用Alistair解決方案手動填充Content-Length標題。