How to get a URL parameter in Express?

Asked

Viewed 2,626 times

2

My URL is coming this way http://localhost:3000/menus/5.5 and it’s bringing all the 5.5 records, but I wish the URL could look like this http://localhost:3000/menus?price=5.5 to have the same result, as you can see below;

inserir a descrição da imagem aqui

The code that makes the query is this;

function getMenus (req, res) {
    var price = req.params.price;
        Menus
        .find({
            price
        }).exec((err, menu)  => {
            if(err){
                res.status(500).send({
                    message: 'Error na solicitação'
                });
            }else{
                if(!menu){
                    res.status(404).send({
                        message: 'Não existe nenhum Reviews nesse registro'
                    });
                }else{
                    res.status(200).send({
                        menu
                    });
                }
            }
        })
    }

Help me fix my controller code. I am not able to get the price value with the quoted URL, http://localhost:3000/menus?price=5.5.

NOTE: Please, the attribute value price cannot be fixed;

NOTE: I need to do the same test with the other attributes that are string.

In the test carried out above was considered this code;

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

See the statement;

inserir a descrição da imagem aqui

According to the above image is being done with the price attribute, but it has to be done with the price and Description attributes of my entity in Node Express.

==========================UPDATING=========================

Following the suggestion, my method became like this;

function pesquisaEspecialMenus (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 });
          }
    }

However the system is showing error in await

As you can see below;

inserir a descrição da imagem aqui

  • sorry but just use req.query nay?

  • 1

    To use the url you mentioned, you would have to change 2 lines of code. your get would have to look like this router.get('/menus', controller.getMenus) and in getMenus the price has q come by query. const price = req.query.price .

  • @AMS it works smoothly with price because price is not string, but it does not happen the same with Description, because the Description attribute of my menu entity is a string and when I put var description = req.query.description and place http://localhost:3000/menus?description=cidade doesn’t work.

  • I get it, I’m gonna run some tests here and I’ll be right back.

  • Let me see why I did some tests here and all worked, when you pass city by query, it does not search in bank is that? Do you want a filter that identifies which data arrived in the query and then search with the related value? Ex: if it is price, search for it and respectively with other types of query, Description, etc; that would be it?

  • @AMS Yes to all your questions

  • You’ve tried it this way: Menus.find(req.params)...?

  • @Sorack didn’t work, it brings all the records but when the URL is entered http://localhost:3000/menu?desciption=errar it does not bring the corresponding records, in fact it lists all the records, so it did not work.

  • But you see, the description is wrong. desciption is not the name of the field.

  • @Sorack sorry, I noticed, tested again, didn’t work. http://localhost:3000/menu?description=duplo

Show 5 more comments

1 answer

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 presented in the parameters of query. To do so you need to use the attribute query of his req:

const { price, description } = req.query;

The second point is that you want to find a text that contain what happens in the description and for that you can use the operator $regex:

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

Now gathering this information and allowing the parameters to be optional we have the following result in your 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 different types of different conditions here.

  • thank you so much for your suggestion. would you check my posting, I just updated it, please.

  • 1

    @wladyband as it is written in error, you can only use await within a method async. Look at the difference of the method statement I made and what you stated. Just change it will work.

  • 1

    Wow, man, in fact, thank you so much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.