How do I get a URL parameter in Express?

2

My URL is coming like this http://localhost:3000/menus/5.5 and it is bringing all the records of 5.5, but I would like the URL to be http://localhost:3000/menus?price=5.5 to have the same result, as you can see below;

Thecodethatmakesthequeryisthis;

functiongetMenus(req,res){varprice=req.params.price;Menus.find({price}).exec((err,menu)=>{if(err){res.status(500).send({message:'Errornasolicitação'});}else{if(!menu){res.status(404).send({message:'NãoexistenenhumReviewsnesseregistro'});}else{res.status(200).send({menu});}}})}

Helpmefixmydrivercode.I'mnotabletogetthepricevaluewiththeURLquoted,http://localhost:3000/menus?price=5.5.

NOTE:Ineedtodothesametestwiththeotherattributesthatarestring.

Intheabovetestweconsideredthiscode;

router.get('/menus/:price',controller.getMenus);

Seethestatement;

Accordingtoimageaboveitisbeingdonewiththepriceattribute,butithastobedonewiththepriceanddescriptionattributesofmyentityinNodeExpress.

===========================UPDATE==========================

Followingthesuggestion,mymethodwaslikethis;

functionpesquisaEspecialMenus(req,res){try{const{price,description}=req.query;letwhere={};if(price){where.price=price;}if(description){where.description={$regex:description,$options:'i'};}constmenu=awaitMenus.findOne(where).exec();//Casonãoencontrenenhumregistroparaabuscaespecificadaif(!menu){constmessage='NãoexistenenhumReviewsnesseregistro';console.error(message);res.status(404).send({message});return;}//Setudocorrerbemres.status(200).send(menu);}catch(e){constmessage='Erronasolicitação.';console.error(e);res.status(500).send({message});}}

Butthesystemisexperiencingawaiterror

Asyoucanseebelow;

    
asked by anonymous 19.08.2018 / 10:39

2 answers

2

Checking the expected result, I see that you have two problems. The first is that you want to get the parameters according to the string displayed in the parameters query . For this you need to use the query attribute of your req :

const { price, description } = req.query;

The second point is that you want to find a text containing what is passed in description and for this you can use the $regex :

{ description: { $regex: description, $options: 'i' } };

Now putting this information together and allowing the parameters to be optional we have the following result in its controller :

const getMenus = async (req, res) => {
  try {
    const { price, description } = req.query;
    let where = {};

    if (price) {
      where.price = price;
    }

    if (description) {
      where.description = { $regex: description, $options: 'i' };
    }

    const menu = await Menus.findOne(where).exec();

    // Caso não encontre nenhum registro para a busca especificada
    if (!menu){
      const message = 'Não existe nenhum Reviews nesse registro';
      console.error(message);
      res.status(404).send({ message });
      return;
    }

    // Se tudo correr bem
    res.status(200).send(menu);
  } catch(e) {
    const message = 'Erro na solicitação.';
    console.error(e);
    res.status(500).send({ message });
  }
}

You can check the Mongoose documentation for a variety of different conditions here .

    
21.08.2018 / 03:09
-1

To catch a query string parameter, you need the object req.query :

const app = require('express')();

// [...]

app.get('/menus', (req, res) => {
  // Assumindo que a requisição será feita para:
  // GET /menus?price=valor
  const { price } = req.params;
  return res.send('Você requisitou o menu com preço de ${price}.');
});

// [...]

To learn more, I suggest you take a look at the documentation:

19.08.2018 / 14:04