2017-05-13 23 views
1

我需要Cors in angularjs, 我沒有使用Cors for webapi,因爲我使用其他人的API, 我只是嘗試使用angularjs以獲得基本的認證數據, 使用郵差它工作正常,我曾經試過,但用我的angularjs應用它不工作 我嘗試了很多,但它顯示如下錯誤:AngularJS呼叫在POSTMAN工作,但不在AngularJS應用工作 - 對預檢請求的響應沒有通過訪問控制檢查

加載資源失敗:服務器響應狀態爲401 (未授權)index.html:1 XMLHttpRequest無法加載 https://api.url/token。對預檢請求的響應未通過 訪問控制檢查:在請求的資源上沒有「Access-Control-Allow-Origin」標頭 。 Origin'http://localhost:63122'是 因此不允許訪問。響應有HTTP狀態代碼401

我曾試圖爲下面的示例代碼:

var myApp = angular.module("myApp", ['ngCookies']); 
myApp.config(['$httpProvider', function ($httpProvider) { 

    $httpProvider.defaults.useXDomain = true; 
    $httpProvider.defaults.withCredentials = true; 
    delete $httpProvider.defaults.headers.common['X-Requested-With']; 
} 

]); 
myApp.controller("GetDataController", ["$scope", "$http", function ($scope, $http) { 
    $scope.GetToken = function() { 
     debugger; 
     var appdata = $.param({ 
      grant_type: 'credentials', 
      scope: 'Customer', 
     }); 

     $http({ 
      async: true, 
      crossDomain: true, 
      method: 'GET', 
      url: 'https://api.url.net/token', 
      data: appdata, 
      headers: { 

       "username": "847fd9f9fg9h7h66jl8ljdggff", 
       "password": "302kfsg7fhhjh0dgjngfdjd", 
       "Authorization": "Basic Mufdnfaffa8439flg8g" 

      } 
     }).then(function (response) { 
      debugger; 
      $scope.displaymessage = response.data; 

     }, function errorCallback(response) { 
      $scope.displaymessage = response; 
      console.log(response) 
     }); 
    }; 

}]) 

,我應該有變化,因爲它是在郵遞員,工作爲什麼它不在我的應用程序工作..

回答

1

CORS在跨域請求的情況下進入圖片。意思是,當一個請求從一個域發送到另一個時。

來自Postman的呼叫不是從domain發送的(因爲Postman就像是一個「獨立」應用程序,而不是一個託管了某個域的網站)。所以CORS在這種情況下不會出現。這是更好地解釋here

但是,您的Angular JS應用必須託管在某個域上。例如,localhostmyexample.com。因此,當您的應用發送相同的呼叫時,它需要CORS。

CORS必須在服務器上實現,而不是在應用程序中實現。服務器必須配置爲接受來自特定域或所有域的呼叫。您將不得不聯繫Web API的所有者,並要求他們實施CORS。

相關問題