Error doing GET search with queries

Asked

Viewed 1,598 times

2

Hello, I created in my application a GET wheel /search, but when I try to send a request with queries by the Inuit application, the node terminal returns two errors, the first is:

Typeerror: Cannot read Property 'split' of Undefined

When analyzing this error I thought the problem was in a function I created to work with arrays and string, follows the function:

function parseStringAsArray(arrayAsString) {
    return arrayAsString.split(',').map(tech => tech.trim())
}

The second error happens when trying to export this function, follows the error:

Unhandledpromiserejectionwarning: Unhandled Promise rejection. This error either originated by Throwing Inside of an async Function without a catch block, or by rejecting a Promise which was not handled with . catch(). To terminate the Node process on unhandled Promise rejection, use the CLI flag --unhandled-rejections=strict (see https://nodejs.org/api/cli.html#cli_unhandled_rejections_mode). (rejection id: 1) (Ode:1804) [DEP0018] Deprecationwarning: Unhandled Promise rejections are deprecated. In the Future, Promise rejections that are not handled will terminate the Node.js process with a non-zero Exit code.

Image of the query:

inserir a descrição da imagem aqui

Route code /search:

const Dev = require('../models/Dev')
const parseStringAsArray = require('../utils/parseStringAsArray')

module.exports

 = {
    async index(request, response) {
        const {
            latitude,
            longitude,
            techs
        } = request.body

        const techsArray = parseStringAsArray(techs)

        const devs = await Dev.find({
            techs: {
                $in: techsArray,
            },
            location: {
                $near: {
                    $geometry: {
                        type: 'Point',
                        coordinates: [longitude, latitude],
                    },
                    $maxDistance: 10000,
                }
            },
        })

        return response.json({
            devs: []
        })
    }
}

NOTE: I’m a beginner in Nodejs so thank you for anyone who tries to help me!

1 answer

1


From the content of your post, it seems to me that this code is from Rocketseat’s Omnistack 10 week.

The split error occurs because it is expecting to receive a string, so it will break the string into an array, using the comma as a separator, for example the string "React,PHP" would create an array with two items ["React", "PHP"]

It would be interesting to post the code of your route "Search", here follows an example that should help you better understand the problem

const Dev                   = require('../models/Dev');
const parseStringAsArray    = require('../utils/ParseStringAsArray');

module.exports = {
    async index (req, resp) {
        // Search devs for techs and distance

        const { lat, long, techs } = req.query;

        const arrayTechs = parseStringAsArray(techs);

        //Programação da rota

    }
};

Note in this example that "lat", "long" and "techs" are the parameters of the URL you sent when calling the search route. If there is no "techs" as parameter, error will occur.

The other error may be because you created an async function but did not use "await", here is an example code:

const Dev                   = require('../models/Dev');
const parseStringAsArray    = require('../utils/ParseStringAsArray');

module.exports = {
    async index (req, resp) {
        // Search devs for techs and distance

        const { lat, long, techs } = req.query;

        const arrayTechs = parseStringAsArray(techs);

         const devs = await Dev.find({
             techs: {
                 $in: arrayTechs,    
             },
             locations: {
                 $near: { // Parametro do mongo para localidade próxima
                     $geometry: { // Objeto que recebe latitude e longitude
                         type: 'Point', // tipo
                         coordinates: [long, lat], // array de numbers
                     },
                     $maxDistance: 10000, // Parametro do mongo para a distância máxima
                 },
             },
        });

        return resp.json({ devs });
    }
};
  • Hello, thank you for the reply, but I tried to make some changes, and when I make the request through India, I only get this result: { "devs": [] }, and not Collection with user data that have the same technologies that I have put in place, what could it be? Also I posted my /search in the publication!

  • You need to change this line : Return Response.json({devs: []}), you are sent by default always an empty array. As you are already searching and storing it in a dev variable, change the line to Response.json({devs}),

  • So, using the request.params I was able to get the results, but to work pro mobile would be with the right request.body? when I use the . body it returns the same errors as before, whatever it might be?

  • Edit: I managed to solve the error, thank you very much Bins, helped me too!!

Browser other questions tagged

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