'Node/express backend crashing when calling the API (MERN stack)

Router:

router.route('/allmovies/:searchtext').get(moviesCtrl.getMovieBySearchText);

Controller:

const getMovieBySearchText = async (req, res) => {
    const searchText = req.params.searchtext;
    const searchedMovies = await Movies.find({ $text: { $search: searchText } }).limit(10).sort({ score: { $meta: "textScore" } });
    if (!searchedMovies) return res.status(204).json({'message': 'No movie found.'});
    res.json(searchedMovies);
}

When I do a search from my frontend, it puts the params in the URL, which the backend grabs. If the search is blank, it will crash the backend server. I can subvert this by setting up a default get for '/allmovies/'. I'm just trying to better understand why this happens, or if there is a better way to handle this. I looked at express validator, but that only made sense for posting data, not getting. Yes, the frontend can be validated, but there are ways around that, and the server won't be safe.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source