Send data in body of POST request

I am trying to send data in the body of a POST request to a RESTful API in my AngularJS application.

My current structure for this request is a controller which grabs data and send this to a service , which then calls the request from its associated factory , as follows:

Controller

userService.saveReport(vm.user.id, searchParams)

Service

service.saveReport = function (id, searchData) {
      var deferred = $q.defer();

      user.saveReport({ userID: id, searchData: searchData }, function(response) {
        deferred.resolve(response);
      }, function(e) {
        deferred.reject(e);
      });

      return deferred.promise;
    };

Factory

    function user($resource, $localStorage, constants) {
    return $resource(constants.API_URL + '/users', { userID: '@userID' }, {
      getReports: {
        method: 'GET',
        url: constants.API_URL + '/users/:userID/reports',
        format: 'json',
        headers: {
          'Accept': 'application/vnd.abp.v1+json',
          'X-Mode': function() {
            return $localStorage.get('mode');
          }
        }
      },
      saveReport: {
        method: 'POST',
        url: constants.API_URL + '/users/:userID/reports',
        format: 'json',
        headers: {
          'Accept': 'application/vnd.abp.v1+json',
          'X-Mode': function() {
            return $localStorage.get('mode');
          }
        }
      }
    });
  }

  angular
    .module('abp')
    .factory('user', user);

})();

I have seen various posts which state $resource allows data: to be send through to form the body of the request, but this doesn't seem to be working. I've tried to add searchData: '@searchData' into the params allowed by the $resource call and then add this into a data section as follows, but this doesn't work (condensed for brevity):

return $resource(constants.API_URL + '/users', { userID: '@userID', searchData: '@searchData' }, {
    saveReport: {
        method: 'POST',
        url: constants.API_URL + '/users/:userID/reports',
        format: 'json',
        data: ':searchData',
        headers: {
          'Accept': 'application/vnd.abp.v1+json',
          'X-Mode': function() {
            return $localStorage.get('mode');
          }
        }
      }
}

How can I send the data of this request in the body of the POST request?


OK, so I've managed to get this working now by changing how I'm sending the searchData in the service . My controller and factory remain unchanged, however I have changed the service to the following, which seems to work absolutely perfectly:

service.saveReport = function (id, searchData) {
      var deferred = $q.defer();

      user.saveReport({ userID: id }, searchData, function(response) {
        deferred.resolve(response);
      }, function(e) {
        deferred.reject(e);
      });

      return deferred.promise;
    };
链接地址: http://www.djcxy.com/p/77652.html

上一篇: $资源发送数据在后期获取

下一篇: 在POST请求的主体中发送数据