Here’s my routing :
router.route('/search:word').get(function(req, res) {
var re = new RegExp(req.params.word, 'i');
console.log(req.params.word);
Place.find().or([{ 'title': { $regex: re }}, { 'category': { $regex: re }}]).sort('title').exec(function(err, places) {
res.json(JSON.stringify(places));
});
});
When I use the request /places/search:test
the console displays :test instead of just "test".
Any idea what’s happening?
Express is a node js web application framework that provides broad features for building web and mobile applications. It is used to build a single page, multipage, and hybrid web application. It's a layer built on the top of the Node js that helps manage servers and routes.
We can easily set up Regex for our Express Router by following these two points: To make our route match with a particular regular expression, we can put regex between two forward slashes like this /<routeRegex>/ Since every route contain /, so wherever we have to use / inside Regex, use a backslash \ / before it.
Express provides methods to specify what function is called for a particular HTTP verb ( GET , POST , SET , etc.) and URL pattern ("Route"), and methods to specify what template ("view") engine is used, where template files are located, and what template to use to render a response.
params property is an object that contains the properties which are mapped to the named route "parameters". For example, if you have a route as /api/:name, then the "name" property is available as req.params.name.
Do you really mean to use router.route('/search:word')
instead of router.route('/search/:word')
? Using colon there seems kind of odd.
If you use router.route('/search/:word')
, and if your request is
/places/search/test
then you get req.params.word="test"
If you want same pattern api end point like eg: /places/search:test
then in api
endpoint you have to use double colon. Example -
router.route('/search::word').get(function(req, res) {
console.log(req.params.word); ---> "test"
});
Thats why you are getting extra colon :test
What's happening here is that it's breaking down the path to /search[word]
. So when you request /search:test
, [word] matches the part after /search
, which would be :test
in that case.
What you probably need instead is something like: /search::word
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With