【问题标题】:Expected response to contain an object but got an array包含对象但得到数组的预期响应
【发布时间】:2014-05-14 11:11:20
【问题描述】:

我收到此错误,我发现许多线程具有相同的消息,但它似乎与我的情况不符,而且我没有经理来解决它。

基本上,在我尝试制作 1 个表单来创建和更新“汽车”对象之前,一切都很好。

这是我的应用程序的演示文稿(使用此模板构建:https://github.com/linnovate/mean):

/public/js/config.js:

[...]
  .state('edit car', {
    url: '/cars/:carId/edit',
    templateUrl: 'views/cars/edit.html'
})
  .state('create car', {
    url: '/cars/create',
    templateUrl: 'views/cars/edit.html'
})

/public/js/services/mycars.js(不知道服务是做什么用的……):

//Cars service used for car REST endpoint
angular.module('mean.mycars').factory('Cars', ['$resource', function($resource) {
return $resource('cars/:carId', {
    carId: '@_id'
}, {
    update: {
        method: 'PUT'
    }
});
}]);

public/js/controllers/mycars.js:

angular.module('mean.mycars').controller('MyCarsController', ['$scope', '$http', '$stateParams', '$location', 'Global', 'Cars',
function ($scope, $http, $stateParams, $location, Global, Cars) {

    $scope.findOneOrCreate = function () {
        // create a new car
        var car = new Cars({
            id : null,
            marque: this.marque,
            modele: this.modele,
            desc: this.desc
        });

        // put new car in scope
        $scope.car = car;

        // if there is a param, search for the car (mode update)
        if ($stateParams.carId !== null){
            Cars.get({
                carId: $stateParams.carId
            }, function(carTmp) {
                       // put the result in scope
                        $scope.car = carTmp;
                    });
        }
    };

   $scope.createOrUpdate = function () {
        var car = $scope.car;

        if (car.id !== null) {
        // update
            if (!car.updated) {
                car.updated = [];
            }
            car.updated.push(new Date().getTime());

            car.$update(function () {
                $location.path('cars/' + car._id);
            });
        }
        else {
            //Create
            car.$save(function (response) {
                $location.path('cars/' + response._id);
            });
        }
    };

最后是我的观点:edit.html:

<section data-ng-controller="MyCarsController" data-ng-init="findOneOrCreate()">
    <form class="form-horizontal col-md-6" role="form" data-ng-submit="createOrUpdate()">
        <div class="form-group">
            <label for="title" class="col-md-2 control-label">Title</label>
            <div class="col-md-10">
                <input type="text" class="form-control" data-ng-model="car.modele" id="title" placeholder="Title" required>
            </div>
        </div>
        <div class="form-group">
            <label for="content" class="col-md-2 control-label">Content</label>
            <div class="col-md-10">
                <textarea data-ng-model="car.marque" id="content" cols="30" rows="10" placeholder="Content" class="form-control" required></textarea>
            </div>
        </div>
        <div class="form-group">
            <div class="col-md-offset-2 col-md-10">
                <button type="submit" class="btn btn-default">Submit</button>
            </div>
        </div>
    </form>
</section>

编辑以添加信息: 网络服务应该只返回一辆车(但不确定是否返回),它们是:

exports.car = function(req, res, next, id) {
Car.load(id, function(err, car) {
    if (err) return next(err);
    if (!car) return next(new Error('Failed to load car ' + id));
    req.car = car;
    next();
});
};

exports.create = function(req, res) {
var car = new Car(req.body);
car.user = req.user;

car.save(function(err) {
    if (err) {
        return res.send('users/signup', {
            errors: err.errors,
            car: car
        });
    } else {
        res.jsonp(car);
    }
});
};

exports.update = function(req, res) {
var car = req.car;

car = _.extend(car, req.body);

car.save(function(err) {
    if (err) {
        return res.send('users/signup', {
            errors: err.errors,
            car: car
        });
    } else {
        res.jsonp(car);
    }
});
};

当我转到 /cars/create 时出现错误消息,而不是在我转到 /cars/:carsId/edit 时出现:

Error: [$resource:badcfg] Error in resource configuration. Expected response to contain an object but got an array
http://errors.angularjs.org/1.2.15/$resource/badcfg?p0=object&p1=array

【问题讨论】:

    标签: javascript node.js angularjs


    【解决方案1】:

    您的网络服务是否返回一个数组? get 方法期望只返回一个对象,如果您要返回某些东西,则与您的 PUT 请求相同。如果您期望多个,则需要在 mycars.js 的服务方法中指定 isArray: true。请参阅此处的示例:http://docs.angularjs.org/api/ngResource/service/$resource

    【讨论】:

    • 我进行了编辑以向您展示我的服务,我认为它们只返回一个对象(但我不确定)。此外:问题是否可能来自控制器中的“$stateParams.carId”,因为当我处于创建模式时它可能为“null”,并且可能会导致错误...
    • 您可以通过打开 Web 开发人员工具栏并查看“网络”选项卡来检查是否返回了多个对象。它应该显示从您的 Web 服务返回的响应。如果您在问题中至少提供了一个 sn-p,那将会很有帮助。此外,您在尝试检索汽车对象之前是否有任何理由创建它?鉴于您的方法称为“findOrCreate”,因此首先调用 Web 服务来检索它,然后如果它为空则创建汽车似乎更有意义。
    • 我已经尝试使用网络(感谢您的提示),它正在我的 /cars 服务上执行获取请求。所以这将返回一个列表,因为 $stateParams.carId 在创建模式下为空。所以问题是这个测试似乎根本不起作用:“if ($stateParams.carId !== null)”。你知道我怎样才能看到 $stateParams.carId 的值(例如,与 java 中的调试模式相同)吗? (PS:是的,我会在创建之前调用 find,这样更合乎逻辑;))
    • 我找到了解决方案,我将测试替换为:“if (typeof $stateParams.carId !== 'undefined')”,一切正常! 'null' 是错误的......不知道为什么,但无论如何它正在工作。
    猜你喜欢
    • 2015-03-11
    • 1970-01-01
    • 2015-08-20
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 2013-12-01
    • 2013-12-17
    • 2016-09-27
    相关资源
    最近更新 更多