根据邮递员的请求发送查询参数

时间:2018-10-04 20:46:22

标签: node.js express

我正在从邮递员向此URL / api / v1 / get_services / p发送获取请求,但是我无法获取查询参数。我得到的结果是[对象对象]。

我的邮递员收到请求看起来像这样:

Postman request: localhost:4000/api/v1/get_services/p?category=Music



Express route:
     apiRoutes.get('/api/v1/get_services/p', async (req, res) => {
      const { category } = req.query;   
      const rootRef = firebase.database().ref(`${category}`);
      await rootRef.once('value', (snap) => {
        if (snap.exists()) {
          console.log(snap.val());
          res.status(200);
          res.send(snap.val());
        } else {
          res.status(404);
          res.send('No services found');
        }
      });
    });

我应该添加一些其他配置来表达中间件吗?

2 个答案:

答案 0 :(得分:1)

编写对象生成器函数以从参数?中获取正确的req.query子元素?

function parameterBuilder (body) {

  var record = {}
  record.category = body.category | ' ';
  record.name  = body.name | ' ';
  return record;

}

 apiRoutes.get('/api/v1/get_services/p', async (req, res) => {
  const { category } = req.query; 
     //New code
    var parameters = parameterBuilder(req.query);
    console.log(parameters) // check to see all ur parameters is there
    //end of new code
      const rootRef = firebase.database().ref(`${category}`);
      await rootRef.once('value', (snap) => {
        if (snap.exists()) {
          console.log(snap.val());
          res.status(200);
          res.send(snap.val());
        } else {
          res.status(404);
          res.send('No services found');
        }
      });
    });

答案 1 :(得分:0)

您的请求应为:

localhost:4000/api/v1/get_services/Music