Angular POST JSON 结构

Angular POST JSON structure

当我从我的 angular 应用程序提交一个空表单时,它会发送以下内容 JSON:

{foo: {}}

这会导致我的服务器出现 500 错误(而不是 422),因为它需要以下结构:

{foo: {bar: ""}}

如何确保 "bar" 键始终包含在我的 JSON 中,即使值为空?

这是我的控制器目前的样子:

$scope.baz = {};
$scope.create = function() {
    var error, success;
    $scope.errors = {};
    success = function() {
      $scope.baz = {};
    };    
    error = function(result) {
        angular.forEach(result.data.errors, function(errors, field) {
            $scope.form[field].$setValidity('server', false);
            $scope.errors[field] = errors.join(', ');
        });    
    };

    Foo.save({ foo: { bar: $scope.baz.bar }}).$promise.then(success, error);

};

我认为当您在 save 请求中传递未定义的对象道具时,它会在向服务器发送请求时被忽略或删除。您可以将该值设置为空值字符串,以确保它被分配了一些值并且不应从请求对象中删除。尝试将您的代码更改为以下内容。

Foo.save({ foo: { bar: $scope.baz.bar|| "" }})