AngularJS: PUT send data with URL but not as JSON data

后端 未结 2 448
南旧
南旧 2021-01-07 12:06

Here is my UserService

angular.module(\'userServices\', [\'ngResource\']).factory(\'User\', function($resource) {
  return $resource(\'/users/:u         


        
相关标签:
2条回答
  • 2021-01-07 12:47

    I would suggest you make the following change to your update declaration:

    {update: {method: 'PUT', data:{profile:'@profile'}, isArray: false}}

    Check out the network tab on this plunker. -v.1.1.5

    Here is the same example on stable version 1.0.7.

    0 讨论(0)
  • 2021-01-07 13:05

    @lucuma answer solved my problem.

    I am sharing the code from my code base which worked after making changes as per @lucuma's suggestion (Thanks a lot @lucuma!)

    The UserService looks like

    angular.module('userServices', ['ngResource']).factory('User', function($resource) {
      return $resource('/users/:userId',
          // todo: default user for now, change it
          {userId: 'bd675d42-aa9b-11e2-9d27-b88d1205c810'},
          {update: {method: 'PUT', data:{}, isArray: false}} // add data instead of params
      );
    });
    

    and ProfileController looks like

    function ProfileController($scope, User) {
        $scope.profile = {};
        $scope.user = User.get();
        $scope.save = function () {
            // I was using $scope.user.$update before which was wrong, use User.update()
            User.update($scope.profile,
                function (data) {
                    $scope.user = data; // since backend send the updated user back
                });
        }
    

    After making these changes, I my network tab in Chrome was as expected

    Request URL:http://localhost:5000/users/bd675d42-aa9b-11e2-9d27-b88d1205c810
    Request Method:PUT
    Status Code:200 OK
    Request Payload:
    {"day_in_month":25}
    
    0 讨论(0)
提交回复
热议问题