我哪里弄错了?

时间:2018-03-15 20:52:44

标签: express

我希望实现一项功能,使用户能够按位置过滤/获取业务。这是我的逻辑:

  1. 声明一个变量来保存已过滤的数组
  2. 循环业务
  3. 如果查询未定义
  4. 调用商家的过滤方法
  5. 如果查询等于数据库中可用的位置
  6. 将具有指定位置的商家推入数组
  7. 使用
  8. 中的商家返回成功消息和状态代码

    指定的位置或带有相应状态代码的错误消息。

    This is the mock database:
    const businesses = [
      {
        id: 1,
        businessName: 'Kulikuli and Sons Limited',
        description: 'We take you to heaven and back',
        email: 'kososhi@gmail.com',
        location: 'Kaduna',
        category: 'Hospitality',
        phoneNumber: '07033288342'
      },
    
      {
        id: 2,
        businessName: 'Rochas Limited',
        description: 'We satisfy all your maintenance',
        email: 'rochas2u@gmail',
        location: 'Lagos',
        category: 'Repairs and Maintenance',
        phoneNumber: '07033288341'
      },
    
      {
        id: 3,
        businessName: 'Lekoto Travels',
        description: 'Travel with us and you won\'t regret it',
        email: 'lekotoboss@gmail.com',
        location: 'Kaduna',
        category: 'Travels and Tours',
        phoneNumber: '07033288344'
      },
    ];
    
    This is the method to control the route: GET /businesses?location=<location>
    static filterByLocation(req, res) {
        const filteredLocation = [];
        for (let i = 0; i < businesses.length; i += 1) {
          if (typeof req.query.location !== 'undefined') {
            businesses.filter((business) => {
              if (business.location === req.query.location) {
                filteredLocation.push(business);
              }
            });
          }
          return res.status(200).send({
            status: 'Success',
            location: filteredLocation
          });
        }
        return res.status(404).send({
          status: 'Fail',
          message: 'Location not found'
        });
      }
    However, the code isn't working as expected. Where am I getting it wrong?
    

1 个答案:

答案 0 :(得分:0)

试试这个,Filter函数返回过滤结果不需要根据条件推入数组,而res.send不返回JSON所以你必须使用res.json()或res.send(JSON.stringify(json) )。你正在返回内部for循环的响应,这将无效。

static filterByLocation(req, res) {
    const filteredLocation = businesses.filter((business) => {
        return business.location === req.query.location;
    });
    if (filteredLocation.length !== 0)
        return res.status(200).json({
            status: 'Success',
            location: filteredLocation
        });
    return res.status(404).json({
        status: 'Fail',
        message: 'Location not found'
    });
}