Sowmay Jain
Sowmay Jain

Reputation: 955

How to get the full dynamic URL in NodeJS?

There is already a similar thread which seems alike but here I've some different problem.

I want the full URL where URL is dynamic. I'm using a common nunjuk template for all of my pages.

Let's face it. Suppose I've an URL path:

/blog/one/two/three

Notably, the "blog" is static but the "one", "two" and "three" are variables which will change as per the requested blog post on my website.

I'm using the following code to get the URL from by passing ":post" but how when I add more path sub-directories like "one", "two" or "three" in the url, I get "template not found" error.

router.get('/blog/:post', function (req, res) {
            var path = req.params.post;

            var title2 = JSONFile[path].title;
            var date2 = JSONFile[path].date;
            var author2 = JSONFile[path].author;
            var content2 = JSONFile[path].content;

            res.render('blogposts.html', {
                    title : title2,
                    date: "date2",
                    author: "author2",
                    content: "content2"
            });
    });

My question is: How can I get all the dynamic URL sub-paths after "/blog"? And remember, the sub-paths may also extend to "four" or "five" and so on.

Upvotes: 1

Views: 3709

Answers (1)

Ishan Jain
Ishan Jain

Reputation: 765

I am assuming that there are 3 parameters in positions of one, two and three and all of them are dynamic and You want to serve some content after using these parameters in code. You can replace it with this,

/blog/:year/:month/:day

This way, All 3 parameters are dynamic and can be accessed like this,

var year = req.params['year'],
    month = req.params['month'],
    day = req.params['day'];

If there are more than 3 parameters in URL then you can append more placeholders like this

/blog/:one/:two/:three/:four/:five 

and all of them can be accessed from req.params

Upvotes: 1

Related Questions