iamsonivivek
iamsonivivek

Reputation: 195

Make dynamic path in node and express js

I am trying to make route dynamic like /review-{title}-{id} , but causing error don't know why, Also if user enter the wrong params than how to handle that. My client requirement is like above, I am not good in node and express please anyone suggested how to make routes like above. Also if I needed to make route like this /review/:title/:id format than how can I make like that.

I am trying but it redirect me out to the 404 page,

Please find my existing code details inside, server.js

this is working.. 
app.get('/review', (req, res) => {
 res.sendFile(path.resolve(__dirname, '../client/review.html'));
});

but not this one..
app.get('/review-*-*', (req, res) => {
 res.sendFile(path.resolve(__dirname, '../client/review.html'));
});

Also not this one working
app.get('/review/*/*', (req, res) => {
 res.sendFile(path.resolve(__dirname, '../client/review.html'));
});

This is 404 page which call evrytime while accessing dynamic pages
app.get('/*', (req, res) => {
 res.sendFile(path.resolve(__dirname, '../client/404.html'));
});

Upvotes: 0

Views: 4230

Answers (1)

Paul
Paul

Reputation: 36349

Check out the syntax for routes in Express.

In most cases you're better off using route params, e.g.:

app.get('/review/:title/:id', (req, res) => {
 res.sendFile(path.resolve(__dirname, '../client/review.html'));
});

Some more flexibility (but more opaque for most developers) would be to match on regex.

I think you can put a * in the middle of words (they give an example like '/abc*def', but I'm not sure how nicely that plays with the other things you're doing, and I don't think you can have multiple *'s in the pattern if you do that.)

Upvotes: 2

Related Questions