0

I am learning react and express framework from NodeSchool.io exercises.
I want to store all exercise files in single application with multiple pages like

index
index2
index3
index4
....

localhost:3000/indexN

But I am unable to set the route for such URLs. Project repo: Git Public Repo URL

Tried various things but could not resolve the issue.
How to configure dynamic routes with express.js

app.use("/indexn*", function(req, res) {
  res.render("indexn", "");
});

API kind of solution works as below but this was also not helpful as its parameterized URL

 // http://localhost:3000/index/2
 app.get('/index/:id', function(req , res){
     res.render('index' + req.params.id, "");
 });

I also tried various RegEx patterns in above function like
(index)n, index:n*
but compilation fails.

Thanks for your help.

1 Answers1

0

You can use a regular expression following the proper syntax (without quotes but using /delimiters/) :

app.use(/\/index.*/, function(req, res) {
  // code
});

This will match any path beginning with "/index". To match only "/index" followed by a number n, use the pattern : /\/index[0-9]*/

You can also match the file path using glob-like pattern : '/index*'.

You can handle the request depending on the actual path being requested by checking on req object.

app.use('/index*', function(req, res) {
  res.render(req.originalUrl);
});

cf. app.use() documentation

EricLavault
  • 12,130
  • 3
  • 23
  • 45
  • Thank you for your answer, but I am not sure how to **render/redirect the page**? I tried to use `res.render("indexn", "");` but it shows error. –  Jan 07 '20 at 18:05
  • 1
    Hi, you can check the actual path being requested using req so that you can render what you need to render depending on it.Tell me if you need more code chunks. (edit) I just reedited my answer with more details. – EricLavault Jan 07 '20 at 18:23
  • I am not sure if its the right way to achieve the purpose. But below code works now and it properly redirects. I examined the request baseUrl and removed the preceding slash from the string to get the exact page URL as below: `app.use('/index*', function(req, res) { console.log(req.baseUrl); res.render(req.baseUrl.replace('/',''), ""); });` –  Jan 07 '20 at 18:29