AngularJS:PUT 发送带有 URL 的数据但不是 JSON 数据 [英] AngularJS: PUT send data with URL but not as JSON data

查看:21
本文介绍了AngularJS:PUT 发送带有 URL 的数据但不是 JSON 数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我的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});
}

但是当我在 Chrome 中看到网络标签时,我看到

But when I see the Network Tab in Chrome, I see

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

如何将其作为 data 有效负载发送?所以 URL

How can I send this as data payload? so that URL is

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

和数据一样

{
  day_in_month: 5
}

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

My endpoint expects the data to be part of request, so that it can parse it as request.json

谢谢

推荐答案

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

@lucuma answer solved my problem.

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

I am sharing the code from my code base which worked after making changes as per @lucuma's suggestion (Thanks a lot @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 中的网络选项卡符合预期

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}

这篇关于AngularJS:PUT 发送带有 URL 的数据但不是 JSON 数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆