简体   繁体   English

AngularJS:PUT使用URL发送数据,但不作为JSON数据发送

[英]AngularJS: PUT send data with URL but not as JSON data

Here is my UserService 这是我的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}}
  );
});

In my controller, I do 在我的控制器中,

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

But when I see the Network Tab in Chrome, I see 但是当我在Chrome中看到“网络”标签时,

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

How can I send this as data payload? 如何将其作为data有效载荷发送? so that URL is 所以URL

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

and data goes as 和数据一样

{
  day_in_month: 5
}

My endpoint expects the data to be part of request, so that it can parse it as request.json 我的端点希望数据是请求的一部分,以便可以将其解析为request.json

Thank you 谢谢

@lucuma answer solved my problem. @lucuma回答解决了我的问题。

I am sharing the code from my code base which worked after making changes as per @lucuma's suggestion (Thanks a lot @lucuma!) 我正在共享我的代码库中的代码,该代码在按照@lucuma的建议进行更改后可以正常工作(非常感谢@lucuma!)

The UserService looks like 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
  );
});

and ProfileController looks like 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
            });
    }

After making these changes, I my network tab in Chrome was as expected 进行这些更改之后,我的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}

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 -v.1.1.5

Here is the same example on stable version 1.0.7 . 这是稳定版本1.0.7上的相同示例。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM