2016-10-18 74 views
0

它工作完美,但有段時間我已經停止了這個項目的工作。我發送一個刪除請求到我的服務器,它給了我這個Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://abc.dev/users/users/18. (Reason: CORS preflight channel did not succeed).(unknown)Angularjs-爲什麼我的DELETE請求會作爲Options?

API是用Yii框架編寫的。我正在使用CORS擴展名爲Firefox,我的GET, POST方法工作得很好,但我的DELETE方法似乎卡住了。

我控制器

$scope.delete = function (id) 
    { 
     if (confirm("Are you sure you want to delete the user") === true) { 
      $http({ 
       method: 'DELETE', 
       url: 'http://abc.dev/users/users/' + id, 
       headers: {'Content-Type': 'application/x-www-form-urlencoded'} 

      }) 
        .success(function (data) { 
         $scope.singleuser = data; 
         console.log("function single user is processed"); 
         $scope.user(); //call the function to reload 
        }) 
        .error(function (data) { 
         console.log('error'); 
        }); 


     } 

我的後端API刪除功能

public function actionDelete() { 
    switch ($_GET['model']) { 
     // Load the respective model 
     case 'users': 
      $model = User::model()->findByPk($_GET['id']); 
      break; 
     default: 
      $this->_sendResponse(501, sprintf('Error: Mode <b>delete</b> is not implemented for model <b>%s</b>', $_GET['model'])); 
      Yii::app()->end(); 
    } 
    // Was a model found? If not, raise an error 
    if ($model === null) 
     $this->_sendResponse(400, sprintf("Error: Didn't find any model <b>%s</b> with ID <b>%s</b>.", $_GET['model'], $_GET['id'])); 

    // Delete the model 
    $num = $model->delete(); 
    if ($num > 0) 
     $this->_sendResponse(200, $num); //this is the only way to work with backbone 
    else 
     $this->_sendResponse(500, sprintf("Error: Couldn't delete model <b>%s</b> with ID <b>%s</b>.", $_GET['model'], $_GET['id'])); 
} 

}

我附上我的網絡的圖像了。 enter image description here

回答

1

您正在執行跨源請求大多數瀏覽器在實際請求檢查Access-Control-Allow-Origin之前發送OPTION請求。如果當前域被允許,則執行該請求。

+0

我已經閱讀了很多,並嘗試了不同的解決方案,但沒有順利。我該怎麼辦 ? –

+1

在您的服務器上處理OPTION以返回正確的Access-Control-Allow-Origin – JEY

0

這是一個服務器端問題。爲了安全並節省服務器負載,Web服務器默認不允許跨源請求。

由於您在本地主機上工作,所以不允許。它應該從現場網站工作得很好。但是,如果您想允許交叉來源,則必須根據您使用的內容對服務器上的NGINX/Apache .conf文件進行更改。

如: 對於Nginx的,你需要幾頭添加到請求

 add_header 'Access-Control-Allow-Origin' "$http_origin"; 
     add_header 'Access-Control-Allow-Credentials' 'true'; 
     add_header 'Access-Control-Allow-Methods' 'GET, POST, PUT, DELETE, OPTIONS'; 
     add_header 'Access-Control-Allow-Headers' 'Accept,Authorization,Cache-Control,Content-Type,DNT,If-Modified-Since,Keep-Alive,Origin,User-Agent,X-Mx-ReqToken,X-Requested-With'; 
+0

感謝您回答確實這是一個服務器端問題。 –

0

這是一個服務器端的問題,本文檔解決我的問題https://gist.github.com/sourcec0de/4237402

相關問題