Reputation: 231
I am very new to MEAN stack development and only started yesterday. I am trying to get my data back from the database with a call using a resource which is linked to a server side controller. But I am receiving the following console error "Error: [$resource:badcfg] Error in resource configuration for action query
. Expected response to contain an array but got an object"
Angular Controller:
app.
controller('ArticleCtrl', function($scope, $location, $resource){
var articles = $resource('/api/articles');
articles.query(function(result){
console.log(result);
});
$scope.addnew = function(){
$location.path("/administrationarea/articles/newarticle");
}
});
Server.js:
articlesController = require('./server/controller/article-controller');
app.get('/api/articles', articlesController.list);
app.post('/api/articles', articlesController.create);
server side controller:
var article = require('../models/articleModel');
module.exports.create = function(req, res){
var art = new article(req.body);
art.save( function (err, result){
res.json(result);
});
}
module.exports.list = function(req, res){
article.find({}, function (err, results){
res.json(results);
});
}
can anyone tell me why this might be happening and maybe offer a solution so that the data is returned as an array instead of an object.
Upvotes: 3
Views: 6545
Reputation: 364
The error is because
var articles = $resource('api/articles');
articles.query(function(result){
// here result should be an array.
console.log(result);
});
here articles.query expects an array. but not an object.
if your api returns an object then you should use articles.get().
articles.get(function(result){
// here result should be an object but not array
console.log(result);
});
$resource.query() is used for getting an array from REST API and $resource.get() is used for getting an object from REST API. but in both cases the request type(/method) is 'get' only.
please refer to the angularJS documentation
Upvotes: 9