AngularJS: PUT用URL发送数据,而不是JSON数据

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

本文关键字:数据 JSON PUT URL AngularJS      更新时间:2023-09-26

这是我的UserService

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', params:{profile: '@profile'}, isArray: false}}
  );
});

在我的控制器中,我使用

$scope.save = function() {
    $scope.user.$update({profile: $scope.profile});
}

但是当我在Chrome浏览器中看到网络选项卡时,我看到

Request URL:http://localhost:5000/users/bd675d42-aa9b-11e2-9d27-b88d1205c810?profile=%5Bobject+Object%5D
Request Method:PUT
Status Code:200 OK

我如何将其作为data有效载荷发送?使URL

http://localhost:5000/users/bd675d42-aa9b-11e2-9d27-b88d1205c810

和data作为

{
  day_in_month: 5
}

我的端点希望数据是请求的一部分,因此它可以将其解析为request.json

谢谢

@lucuma的回答解决了我的问题。

我从我的代码库中分享代码,这些代码在按照@lucuma的建议进行更改后工作(非常感谢@lucuma!)

UserService看起来像

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
  );
});

ProfileController看起来像

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
            });
    }

在进行这些更改后,我在Chrome浏览器中的网络选项卡如预期的

Request URL:http://localhost:5000/users/bd675d42-aa9b-11e2-9d27-b88d1205c810
Request Method:PUT
Status Code:200 OK
Request Payload:
{"day_in_month":25}

我建议你对你的更新声明做如下修改:

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

查看这个柱塞上的网络标签。-v.1.1.5

下面是稳定版1.0.7的相同示例