简体   繁体   English

使用Express.js和Mongoose的基本GET请求

[英]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. 任何帮助将不胜感激。

  • Make sure that the middleware function (the code for GET request) is mapped to /api/listings 确保将中间件功能(用于GET请求的代码)映射到/api/listings
  • I'm not sure about exports.list . 我不确定exports.list It should probably be module.exports 它可能应该是module.exports
  • I'm assuming, based on ur code, that ur using the mongoose ODM. 我基于您的代码,假设您使用猫鼬ODM。 In which case, I think you need to pass a query to the find method check this out 在这种情况下,我认为您需要将查询传递给find方法, 请检查一下
  • You might wanna make sure that you're connected to the database at the time of test initialization and that that completes before the test starts 您可能想要确保在测试初始化​​时已连接到数据库并且该连接在测试开始之前已完成
  • It always helps to log errors 它总是有助于记录错误

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM