[英]Basic GET Request using Express.js & Mongoose
I'm working on an assignment to list all of the data in a mongoDB database, and am having trouble finding where I'm going wrong. 我正在分配一个任务,以列出mongoDB数据库中的所有数据,但无法找到我要去哪里。 It seems like a fairly simple problem, but whenever I run the provided mocha test, it keeps throwing 404 errors.
这似乎是一个相当简单的问题,但是每当我运行提供的mocha测试时,它都会不断抛出404错误。 Here is the relevant portion of the test:
这是测试的相关部分:
it('should it able to retrieve all listings', function(done) {
agent.get('/api/listings')
.expect(200)
.end(function(err, res) {
should.not.exist(err);
should.exist(res);
res.body.should.have.length(147);
done();
});
});
And here is my code for the GET request. 这是我的GET请求代码。 I've tried a few different ways of coding it, but this is seems like the simplest/most direct way to return the desired data as JSON.
我尝试了几种不同的编码方式,但这似乎是将所需数据作为JSON返回的最简单/最直接的方式。
exports.list = function(req, res) {
Listing.find(function(err, listing){
if(err){
res.status(404).send(err);
} else {
res.json(listing);
}})
};
Is there anything else I should be doing? 我还有什么需要做的吗? I've been looking at tutorials and basic examples of requests and it seems like it should work, but it doesn't.
我一直在研究请求的教程和基本示例,看来它应该可以工作,但事实并非如此。 Any help would be greatly appreciated.
任何帮助将不胜感激。
/api/listings
/api/listings
exports.list
. exports.list
。 It should probably be module.exports
module.exports
Checkout express-generator to scaffold a boilerplate express app. Checkout Express-Generator可以搭建样板Express应用程序。 Might help to compare it with your app, to check if it's wired correctly
可能会帮助您将其与您的应用程序进行比较,以检查其接线是否正确
Seems like you are not passing the first parameter to the find method . 似乎您没有将第一个参数传递给find方法 。 Only the callback ... try this:
仅回调...请尝试以下操作:
Listing.find({}, function(err, listing) {
if (err) {
res.status(404).send(err);
} else {
res.json(listing);
}
})
I am assuming you want all records which is why we pass an empty object {} . 我假设您想要所有记录,这就是为什么我们传递一个空对象{}的原因 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.