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'));
});
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.)
Related
I'm a bit confused about the Express priority order for all the routes.
This is what I've done following some stackoverflow answers and other guides on internet.
I have some http requests and this is the order: is it right in your opinion? If not, why? Thanks!
app.get('/', (req, res) => {
...
});
app.get('/:car', (req, res) => {
...
});
app.get('/:car/:eng', (req, res) => {
...
});
app.put('/:car/:feature_id', (req, res) => {
...
});
app.get('/import/colors', (req, res) => {
...
});
app.post('/import/brands', (req, res) => {
...
});
app.post('/import/colors/:car_id', (req, res) => {
...
});
Express just attempts to match your routes in the order they are defined in your code for the type of request it is (.e.g GET, POST, PUT). So, if it's a GET request, Express matches only against the route definitions that include GET. Here's a few examples from the routes you show.
If there's an incoming route of /hello/there, then that will first match app.get('/:car/:eng', ...) because that matches ANY two segment path and it's the first route in order that matches.
If there's an incoming route of /import/colors, then that will also match app.get('/:car/:eng', ...) because that matches ANY two segment path.
If, on the other hand, you change the order of the code to this:
app.get('/import/colors', (req, res) => {
...
});
app.get('/:car/:eng', (req, res) => {
...
});
Then, /import/colors will match the first of these two routes because matching is tried in the order the routes are declared.
FYI, in general, I don't like using routes that have a top level wildcard because you get yourself all sorts of possible conflicts and you may find yourself boxed into a bit of a corner for future URL expansion when you want to add other routes.
Recommendation
So, if you have overlapping route definitions, then define the most specific routes first so they get a chance to match before the more general routes. Most of the time, I prefer a URL design that doesn't have overlapping routes and then you won't have this issue at all.
Alright, so I am trying to serve a ejs file to be rendered. This file is inside a different directory, so when I try to write that path it still doesn't work. Here is the problematic code:
app.get('/views2/personal-form', (req, res) => {
res.render('/views2/personal-form');
});
My ejs page is inside the folder views2 inside of the folder views. So as an example all of these following routes minus the one listed above are served:
app.get('/back-home', (req, res) => {
res.render('back-home');
});
app.get('/business', (req, res) => {
res.render('business')
});
app.get('/account', (req, res) => {
res.render('account');
})
app.get('/personal-form', (req, res) => {
res.render('personal-form')
});
I have tried putting the line of code with personal-form in it in numerous places and to no avail. Any recommendations/suggestions would be greatly appreciated. In the picture, you can see the two 'views' folders. I just want to be able to serve view files from multiple view directories so I can organize my app better.
Ok never-mind I just got it.
app.get('/personal-form', (req, res) => { res.render('views2/personal-form') });
I want to get the url /view/:id quite similar like in this question. The only answer I found satisfying was from HagenAnuth by using req.originalUrl. Unfortunately this does not work for static resources.
app.use('/view/:id', (req, res, next) => {
console.log(req.originalUrl); // -> returns js file and not e.g. /view/25
next();
}, express.static(path.join(__dirname, 'views')));
Is there nowadays a good way to do this?
I tried to replace the / path with another callback:
app.get('/', (req, res) => res.send('Hello World!'))
app.get('/', (req, res) => res.send('404'))
But when I navigate to / path it still responds with Hello World! instead of 404, so that means that the callback was not replaced. So is there any way to do this?
Clarification:
What I actually want to do is to delete routes at runtime, but replacing callbacks with something that respond with say 404 would also do the trick.
It's not clear from your question, but it looks like you have both routes present in your code. If that is the case, then only the first one will be used.
If you are trying to set up some sort of dynamic routes (ie. replace the route handler completely after the application starts), I'm not sure that is possible in Express. According to this comment on deleting Express routes at runtime, it appears that the routes are optimized when the application is first initialized and there is no easy way to change them after that.
If you need a route to behave differently at runtime, the way to do it is in the route callback. For example:
app.get('/', (req, res) => {
// test something & respond accordingly
if (req.query.someValue === 'do this') {
return res.send('Hello world');
}
// otherwise, return a 404 error
return res.status(404).send('No way, man!');
});
I have an HTML file (privacy.html) and I want to serve it as home. I wrote the following:
app.get('/', (req, res) => {
res.writeHead(200, {'Content-Type': 'text/html'})
res.write(require('./privacy.html'))
res.end()
})
What is wrong?
This may be what you are looking for:
app.get('/', function(req, res){
res.sendFile(__dirname + '/privacy.html');
});
You don't use require to include html. Take a look at express's res.sendFile and express.static. It looks like you probably want the latter, but the former is the more flexible one if you're sure you want the structure you have.
Here's a little more information about require and the module system.
Edit: I urge you to read the links I provided, but I'll give you some code to use anyway so you don't end up using bad techniques.
The full implementation is super-simple:
// Somewhere above, probably where you `require()` express and friends.
const path = require('path')
// Later on. app could also be router, etc., if you ever get that far
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'privacy.html'))
})
// If you think it's still readable, you should be able rewrite this as follows.
app.get('/', (req, res) => res.sendFile(path.join(__dirname, 'privacy.html')))
There are ways to make this fancier (bindings, etc.), but none of them are worth doing when this works fine as-is. This will work everywhere that express does, including on systems where the path delimiter/file system hierarchy is different.
app.get('/', function(req, res){
res.sendFile(__dirname + 'privacy.html');
});
Here is a good example: https://codeforgeek.com/2015/01/render-html-file-expressjs/