mrybak3
mrybak3

Reputation: 425

Dynamic URL with static routing in Express

I want to statically render a page that uses a dynamic url in Express.

Specifically,

I have a forum where users make posts, and each post has a dynamic url that displays the post when a user clicks the associated anchor link:

localhost:8080/posts/postNumber

I have a static html page localhost:8080/posts/.

I want the dynamic links the user clicks to render the static page localhost:8080/posts/, but display the url localhost:8080/posts/postNumber, so that I can then use the post number with an AJAX request.

Is there any way to do this without dynamic rendering as I am trying?

Upvotes: 0

Views: 225

Answers (1)

Mark
Mark

Reputation: 92440

You can define url parameters like this:

app.get('/posts/:postNumber/', function (req, res) {
   // do stuff (or not) with req.params which will have
   // {postNumer: yourValue}

    var options = {
        root: __dirname + '/public/',
        dotfiles: 'deny',
        headers: {
          'x-timestamp': Date.now(),
          // other headers you might want
        }
    };

    var fileName = 'staticFileName';
    res.sendFile(fileName, options, function (err) {
       if (err) {
         next(err);
       } else {
         console.log('Sent:', fileName);
       }
    })
})

This will match /posts/[anything_you_want] and send the filename specified its fileName in the directory specified in the options. This based on the express 4 docs here: http://expressjs.com/en/api.html#res.sendFile

Upvotes: 1

Related Questions