Home > Net >  Cannot read properties of undefined (reading 'toLowerCase')
Cannot read properties of undefined (reading 'toLowerCase')

Time:01-02

what I'm trying to do here is a post-search method that takes an input from the search textbox in the .ejs file and renders searchresults page but whenever I try it gives me an error Cannot read properties of undefined (reading 'toLowerCase')

let allPlaces = ['annapurna', 'bali', 'inca', 'paris', 'rome', 'santorini'];
    app.post('/search', function (req, res) {
        let z = req.body.search;
        MongoClient.connect("mongodb://127.0.0.1:27017", function (err) {
            if (err) throw err;
            // let db = client.db('myDB');
            // let collection = db.collection('myCollection');
            let searchresult = [];
    
            for (let j = 0; j < allPlaces.length; j  ) {
    
                if (allPlaces[j].includes(z.toLowerCase())) {
                    searchresult.push(allPlaces[j]);
    
                }
            }
            if (searchresult.length === 0) {
                alert("Can't find what you are looking for");
            }
    
            res.render('searchresults', {place: searchresult});
    
        });
    });

CodePudding user response:

Make sure the let z = req.body.search; is always available,

default it to a string as follows:

let z = req.body.search ?? ''; 

req.body.search is not a string, did you use the express.use(express.json()) middleware? Are you sure the client is sending the string?. Make sure you're doing that. And in case there wasn't a search string, you should make a default for it, an empty string is enough "".

Or you can have an if statement to detect:

if(typeof req.body.search !== "string") throw new Error("please privde a search term")

CodePudding user response:

Make sure the let z = req.body.search; is always available, default it to a string as follows:

let z = req.body.search ?? ''; req.body.search is not a string, did you use the express.use(express.json()) middleware? Are you sure the client is sending the string?. Make sure you're doing that. And in case there wasn't a search string, you should make a default for it, an empty string is enough "".

or you can have an if statement to detect:

if(typeof req.body.search !== "string") throw new Error("please privde a search term")

  • Related