How to serve a dynamic html page with static content using express

871 views Asked by At

I am using express to statically serve html pages as follows:

app.use( express.static('./public',{extensions:['html']}))

However I have an html page Account.html and I would like to pass parameters to it to populate it as necessary, something like: "/Account?id=123" and then based on this id return a json object with the necessary data, however I am a bit confused on how you would do this, since Account.html is a static page my custom get route app.get('/Account', async (req, res) => is not being hit and instead I get the static Account.html file served, however I found if instead I use a URL format as follows: "/Account/?id=123" (with the extra slash before the parameters) then the /Account route gets hit, and I am able to fetch the data from the database, the problem now is how can I inject that data into the Account.html page?

1

There are 1 answers

0
Samuel Goldenbaum On BEST ANSWER

Your route for the scenario above should be:

app.get('/account:id', (req, res) => {
   // depending on the method you used, you can access the id like: req.body.id, req.params.id
   ...process and eventually 
   res.render('account', { data: data });
});

res.render('account'... will render a view called account you have defined and pass the data to it to use.

You would hit this route like:

<a href="/account/100">account</a>

All pretty standard stuff and well documented on the main express website