2014-02-10 46 views
2

我在設置標題發送請求到spring mvc時遇到問題。下面是我的代碼來設置標題,但我仍然收到此錯誤。

OPTIONS http://localhost/orgchart/app/json/depts 403 (Forbidden) angular.js:7978 
OPTIONS http://localhost/orgchart/app/json/depts No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. angular.js:7978 
XMLHttpRequest cannot load http://localhost/orgchart/app/json/depts. No 'Access-Control- Allow-Origin' header is present on the requested resource. Origin 'http://localhost:8080' is therefore not allowed access. 

我的角碼是在下面,有什麼想法嗎?

orgChartApp.factory('Depts', function($http) { 
    $http.defaults.headers.put = { 
     'Access-Control-Allow-Origin': '*', 
     'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', 
     'Access-Control-Allow-Headers': 'Content-Type, X-Requested-With' 
    }; 
    var departmentService = { 
     putDepartment: function(dept) { 
      var promise = $http.put('http://localhost/orgchart/app/json/depts', { 
       name: dept.name, 
       parentDepartmentId: dept.parentDepartment.id, 
      }).then(function(response) { 
       return response.data; 
      }); 
      return promise; 
     } 
    }; 
    return departmentService; 
}); 
+1

這些標頭需要在服務器上而不是客戶端上。出於顯而易見的原因,您不能配置CORS客戶端。 –

+0

我確實有CORS過濾器設置,並在Spring MVC後端工作,但它適用於得到 – kotsumu

+0

錯誤消息似乎表明,在這個調用'http:// localhost/orgchart/app/json/depts'服務器沒有返回CORS標題:'訪問控制 - 允許原點'。您應該使用提琴手代理請求(或直接通過Postman調用)並查看服務器返回的內容。 –

回答

0

我解決了這個問題,首先所以這是一個很大的問題,如果我期待任何返回值我的服務器的終點未返回ResponseBody的。其次,我發送單個參數,並確保爲我的後端添加一個標題,如下所示。

putDepartment: function(dept) { 
     var promise = $http({ 
      url: 'http://localhost/orgchart/app/json/dept/' + dept.id, 
       method: 'PUT', 
       params: { 
        name: dept.name, 
        parentDepartmentId: dept.parentDepartment.id 
       }, 
       headers: { 
        'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8' 
       } 
      }).then(function(response) { 
       return response.data.depts; 
      }); 
      return promise; 
    }