Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I get colon with my param using express for node.js

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?

like image 899
Genjuro Avatar asked May 10 '14 01:05

Genjuro


People also ask

What is Express () in node JS?

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.

How use regex in Express JS?

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.

What is the use of Express ()?

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.

What is Param in Express JS?

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.


3 Answers

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"

like image 187
Ben Avatar answered Oct 22 '22 17:10

Ben


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

like image 5
Jaisa Ram Avatar answered Oct 22 '22 16:10

Jaisa Ram


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

like image 4
mscdex Avatar answered Oct 22 '22 16:10

mscdex