what does following path means "/^\/.*/" in get function of Express? - node.js

I am new to programming and have been reading Node.js code.
I don't understand what does the path /^\/.*$/ means in the following function.
app.get(/^\/.*$/, function(req, res) {
res.sendFile(__dirname + indexPath)
})

That is a regex which matches the character / and any other, or no characters following it. In short, it will catch all request paths.
Regex101 is a great tool for building and deciphering regexes, I recommend you take a look.
Good luck!

Related

Invalid Regular Expressions in Express, '/(new)?' - Invalid group

I have the code
app.get('/(new)?', (req, res) => {}
Express returns a SyntaxError: Invalid regular expression: /^\/(?(?:([^\/]+?)))?\/?$/: Invalid group
I did a little of Troubleshooting and found out that the problem is somehow between the slash and brace. If I do app.get('/e(new)?', (req, res) => {} it works just fine...
How can I get around this? Why does this occur?
Please don't hate me for anything stupid I might have done or not finding something on it...
I am using Express 4.17.1.
Use a RegExp literal instead of encapsulating it in a string:
app.get(/\/(new)?/, (req, res) => {}
It's tough to say exactly why this works over what you had originally, but my best guess is that there you've hit a small edge case in the way that these faux-RegExp patterns are interpreted in Express' route signature parser that is not triggered when expressing the pattern literally this way.
If you're so inclined, you may consider reporting this as an issue in Express' GitHub repository - some of the more involved contributors may be able to pinpoint exactly where in the codebase this pattern causes issues.

how to fetch req.params whatever it was

I'm working on a url shortener api. The problem i'm facing is that if I pass a parameter like https://www.youtube.com/watch?v=8aGhZQkoFbQ then req.params.url will only be equal to https://www.youtube.com/watch. I've looked a lot on stackoverflow and all the answers are similar but not what I'm looking for.
I want to parse the url parameter and get the characters it contains.
This is the URI i'm using right now
router.route('/add/:url(*)')
You can try something like this:
app.get(/[/]add[/].*/, function (req, res) {
var uri = req.originalUrl.replace(/^[/][^/]*[/]*/, '');
console.log(uri);
res.end();
});
Maybe you're wanting the query part of the URL? Take a look at req.query docs (and other parts of the request) and read about the parts of the URI or more formal definitions on wikipedia. Having the correct names will help you understand the Express.js docs.
From express.js docs:
// GET /search?q=tobi+ferret
req.query.q
// => "tobi ferret"
From wikipedia:
scheme:[//[user:password#]host[:port]][/]path[?query][#fragment]

How can I allow slashes in my Express routes?

I'm attempting to implement permalinks, in the form /2013/02/16/title-with-hyphens. I'd like to use route parameters. If I try the following route:
app.get('/:href', function(req, res) { });
...then I get a 404, presumably because Express is only looking for one parameter, and thinks that there are 4.
I can work around it with /:y/:m/:d/:t, but this forces my permalinks to be of that form permanently.
How do I get route parameters to include slashes?
It seems that app.get("/:href(*)", ...) works fine (at least in Express 4). You will get your parameter value in req.params.href.
It will also be fired by / route, which is probably not what you want. You can avoid it by setting app.get('/', ...) elsewhere in your app or explicitly checking for an empty string.
Use a regular expression instead of a string.
app.get(/^\/(.+)/, function(req, res) {
var href = req.params[0]; // regexp's numbered capture group
});
Note that you cannot use the string syntax (app.get('/:href(.+)')) because Express only allows a small subset of regular expressions in route strings, and it uses those regular expressions as a conditional check for that particular component of the route. It does not capture the matched content in the conditional, nor does it allow you to match across components (parts of the URL separated by slashes).
For example:
app.get('/:compa([0-9])/:compb([a-z]/')
This route only matches if the first component (compa) is a single digit, and the second component (compb) is a single letter a-z.
'/:href(.+)' says "match the first component only if the content is anything", which doesn't make much sense; that's the default behavior anyway. Additionally, if you examine the source, you'll see that Express is actually forcing the dot in that conditional to be literal.
For example, app.get('/:href(.+)') actually compiles into:
/^\/(?:(\.+))\/?$/i
Notice that your . was escaped, so this route will only match one or more periods.
You can do this with regex routing
app.get('/:href(\d+\/\d+\/\d+\/*)', function(req, res) { });
I don't know if the regex is right, but you get the idea
EDIT:
I don't think the above works, but this does
app.get(/^\/(\d+)\/(\d+)\/(\d+)\/(.*)/, function(req, res) { });
Going to http://localhost:3000/2012/08/05/hello-i-must-be yeilds req.params = [ '2012', '08', '05', 'hello-i-must-be' ]
You can use this if your parameters has include slashes in it
app.get('/:href(*)', function(req, res) { ... })
It works for me. In my case, I used parameters like ABC1/12345/6789(10).
Hopefully this useful.

Several individual static directories with different paths using Express

I would like to be able to get Express to treat several directories (not just one) as "static" -- that is, if the file is there, then serve it.
Connect's static() module seems to be geared up for people who want to make files in a specific directory available in the server's root. However, that's not what I want. What I am after, is end up with something like this:
GET /modules/MODULE1 -> Return files in modules/MODULE1/public
GET /modules/MODULE2 -> Return files in modules/MODULE2/public
GET /modules/MODULE3 -> Return files in modules/MODULE3/public
I am looking at the source of static, which in turns uses send, which in turns defines SendStream, which takes the file path straight from the request (which is not what I want).
Are there easy ways to do this?
Merc.
what's wrong with
app.use('/modules/MODULE1', express.static('modules/MODULE1/public'))
for each module?
The answer is here:
https://groups.google.com/forum/?fromgroups=#!topic/express-js/kK9muR0mjR4
Basically:
var st = express.static(
__dirname + app.set('path.static'),
{ maxAge : app.set('static.expiry') }
);
app.get(/^\/static\/(v.+?\/)?(.+$)/, function (req, res, next) {
req.url = req.params[1];
st(req, res, next);
});
Basically, since Static consider req.url, it's a matter of hacking it so that it "looks right" when/if the path matches.
I asked TJ if he would add it as an option, he (rightly) answered:
this isn't something send() should do, you can already do this easily with connect/express with several static() middleware, you would just have to do the same but more manual with send()
https://github.com/visionmedia/send/issues/10#issuecomment-8225096

Create a route for any four digit number ie site.com/3434

I would like to create a route that allows for any four digit number to be passed into the URL (www.site.com/3434). I've been unable to figure this out from the express docs and am just learning it for the first time.
I pieced together something based on google searches, but it isn't correct and I don't have enough regex knowledge yet.
app.get(/^[0-9]{4,4}$/, function(req, res){
res.render('mobile');
});
Any help would be appreciated.
You probably want this:
app.get('/:id([0-9]{4})', function(req, res){
res.render('mobile');
});

Resources