$ http设置标头错误 - angularjs

时间:2014-02-10 16:11:02

标签: javascript angularjs http rest

我遇到设置标头以向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 个答案:

答案 0 :(得分: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;
    }