Express routes regex - correct syntax - express

I looked at the following posts but they did not help with this. It's probably simple, alas...
Express routes parameter conditions
https://forbeslindesay.github.io/express-route-tester/
I have the following regex - /^\d+x\d+/i. I want a number separated by an x, so a route would be /100x100,
The regex works on it's own, but not as a route. I tried various escapeings but I keep getting a 404 back. What would be the correct syntax? (I tried something like this already router.get('/\/^\d+x\d+/i'))
PS - As my plan is only to accept digit x digit, I'd be happy to hear about any flaws in this regex.

That's an interesting problem. This is one solution to achieve what you are looking for.
router.get('^/:dimensions([0-9]+[x][0-9]+)', function(req, res) {
//to show you that it hits the route and what it catches
res.send('Route match for dimensions: ' + req.params.dimensions);
});

Related

Dynamic url segments with ExpressJS

When I needed to add a dynamic segment to the URL, the first thing that came to mind was to try the following:
app.get('/one/*/two/*/three', (req, res, next) => {
// req.params as any)[0] - first dynamic segment
// req.params as any)[1] - second dynamic segment
});
Turns out, the code above works perfectly. What confuses me, however, I cannot find it anywhere in the official documentation, and any answer here about dynamic segments with ExpressJS suggests different things, none of them suggest use of asterisks.
Am I doing something wrong here? Or what am I missing?
From the official documentation about Routing:
Route paths
Route paths, in combination with a request method, define the
endpoints at which requests can be made. Route paths can be strings,
string patterns, or regular expressions.
The characters ?, +, *, and () are subsets of their regular expression
counterparts. The hyphen (-) and the dot (.) are interpreted literally
by string-based paths.
And:
This route path will match abcd, abxcd, abRANDOMcd, ab123cd, and so
on.
app.get('/ab*cd', (req, res) => { res.send('ab*cd') })

Can vue-router use regex route matching and pass the match as a named parameter

Under the hood, I understand the vue-router uses path-to-regexp to handle route matching.
If I use the route format:
/app/:collection(/^cases$?)/:id
This matches the route /app/cases/abc123 and directs to the component just fine but doesn't store { collection: 'cases' } on the $route.params object which is what I also need. Is there another way to do this?
My bad, I misunderstood the syntax of path-to-regexp in the docs.
The route matching should have been:
/app/:collection(cases)/:id
.. then you get the route matching with the parameter passed.
I'm unclear if its appropriate to answer the question as correction or delete it. I'm sure someone will let me know ;)

Cypress Assertion

I have a question regarding Cypress assertions, just recently start playing with this testing platform, but got stuck when the URL returns a random number as shown below.
/Geocortex/Essentials/REST/sites/SITE?f=json&deep=true&token=SK42f-DZ_iCk2oWE8DVNnr6gAArG277W3X0kGJL1gTZ7W5oQAAV9iC4Zng4mf0BlulglN-10NK&dojo.preventCache=1575947662312
As you can see token is random and dojo.preventCache is also a random string. I want to detect this url and check if deep=true regardless the token number, but I don't know how to achieve this.
cy.location('origin', {timeout: 20000}).should('contain', '/Geocortex/Essentials/REST/sites/SITE?f=json&deep=true&token=**&dojo.preventCache=**');
Anyone any idea?
You can check both the path and query like this (note that cy.location('origin') doesn't yield neither pathname nor query from your original question, so I'm using cy.url()):
cy.url()
.should('contain', '/Geocortex/Essentials/REST/sites/SITE')
.should('contain', 'deep=true');
or check each separately:
cy.location('pathname').should('contain', '/Geocortex/Essentials/REST/sites/SITE');
cy.location('search').should('contain', 'deep=true');
or, use a custom callback in which you do and assert whatever you want:
cy.url().should( url => {
expect(/* do something with url, such as parse it, and access the `deep` prop */)
.to.be.true;
});

Nuxt encode/decode URI with double colon

My URLs have double colon on them.
I push a path to Nuxt router which has : as a part of it.
export default {
router: {
extendRoutes (routes, resolve) {
routes.push({
name: 'custom',
path: 'towns' + '(:[0-9].*)?/',
component: resolve(__dirname, 'pages/404.vue')
})
}
}
}
When I point to http://localhost:3000/towns:3 , for example, the : is translated as %3Aon the URL leading to this error message:
Expected "1" to match ":[0-9].*", but received "%3A2"
How to revert this to : ?
I tried encodeURI(), decodeURI(), encodeURIComponent() and decodeURIComponent() in vain.
A demo for the ones who wants to try: nuxt-extend-routes
Any suggestions are welcome
Vuex is using vue-router and vue-router is using path-to-regexp to parse router path configuration
It seems to me, that you are trying to use Unnamed Parameters which doesn't make sense because vue-router/vuex need the name of the parameter to pass it down to Vue component behind the route
Why don't just use named parameters ?
{
path: '/towns:id(:\\d+)',
name: 'Page 3',
component: Page3
}
Sure, result will be that $route.params.id value will be prefixed with : and all router-link params must be :XX instead of 'XX' but that's something you can deal with. vue-router (path-to-regexp) is using : to "mark" named path parameters ...there's no way around it
You can take a look at this sandbox. Its not Nuxt but I'm pretty sure it will work in Nuxt same way....
Update
Well it really doesn't work in Nuxt. It seems Nuxt is for some reason applying encodeURIComponent() on matched path segments and throws an error. It works when server-side rendering tho (it throws some error on client still)...
Firstly, I concur with Michal LevĂ˝'s answer that there's a library bug here. The line throwing the error is here in the Nuxt source:
https://github.com/nuxt/nuxt.js/blob/112d836e6ebbf1bd0fbde3d7c006d4d88577aadf/packages/vue-app/template/utils.js#L523
You'll notice that a few lines up the segment is encoded, leading to : switching to %3A.
However, this line appears to have originated from path-to-regexp:
https://github.com/pillarjs/path-to-regexp/blob/v1.7.0/index.js#L212
It isn't trivial to fix this bug because the encoding is not simply 'wrong'. There's a lot of stuff going on here and by the time that line is reached the parameter values have been URL decoded from their original values. In the case of our unencoded : that causes problems but in other cases, such as matching %3A, the encoding would be required.
The handling of encoding within path-to-regexp is a delicate topic and we aren't helped by the old version being used. This also makes it more difficult to come up with a suitable workaround in your application.
So, let's see what we can do...
To start with, let's consider the path:
path: 'towns' + '(:[0-9].*)?/',
Bit odd to concatenate the strings like that, so I'm going to combine them:
path: 'towns(:[0-9].*)?/',
The / on the end isn't hurting but it seems to be unnecessary noise for the purposes of this question so I'm going to drop it.
On the flip side, not having a / at the start can cause major problems so I'm going to add one in.
The .* is suspicious too. Do you really mean match anything? e.g. The current route will match towns:3abcd. Is that really what you want? My suspicion is that you want to match just digits. e.g. towns:3214. For that I've used [0-9]+.
That leaves us with this:
path: '/towns(:[0-9]+)?',
Now, the : problem.
In general, route paths are used in both directions: to match/parse the URL and to build the URL. Your use of an unnamed parameter makes me wonder whether you only intend to use this route for matching purposes.
One option might be this:
path: '/towns:([0-9]+)',
By moving the : outside the parameter it dodges the encoding problem.
There are two problems with the code above:
The colon/number suffix is no longer optional on the URL. i.e. It won't match the path /towns as the original route did. This can be solved by registering /towns as a separate route. I'm not aware of any other way to solve this problem with the available version of path-to-regexp.
You won't be able to use it to build URLs, e.g. with nuxt-link.
If you need to be able to use it to build URLs too then you could use a named parameter instead:
path: '/towns::town([0-9]+)',
The :: part here is potentially confusing. The first : is treated literally whereas the second : is used as a prefix for the town parameter. You might then use that with nuxt-link like this:
<NuxtLink :to="{ name: 'custom', params: { town: 4 } }">
...
</NuxtLink>

MVC multiple parameter routing

I've been trying to pull the parameters passed into a page so I can post it back in Context.
So far,
ViewBag.Message = string.Format("{0}::{1}::{2}",
RouteData.Values["controller"],
RouteData.Values["actions"],
RouteData.Values["id"]);
works with anything simple like "66" or "tt" but anything more complex like "?name=blargh?viewId=66" and it fails.
I've tried a bunch of different ways to see if I could strike gold but nothing seems to work so does anybody have any idea what I'm missing/doing wrong/should be doing instead?
" but anything more complex like "?name=blargh?viewId=66" and it fails.
This doesn't seem to be routing information but query string which you should retrieve from the Request.QueryString bag.
If the {id} parameter is part of your route (as the default routes {controller}/{action}/{id}) I hope you realize that this id cannot be anything you like just because there are rules for an url. For example it cannot contain ? because this symbol has an entirely different meaning in an url - it represents the query string separator.