I have an express route that handles localhost:3000/test. I want everything after this that doesn't have a period to render with the same router.get command. I'm struggling to figure out the correct Javascript regex string.
router.get('/test/:path[\s^.]*$', function () {
//res.render etc
}
So, when I visit localhost:3000/test/math or localhost:3000/test/math/geometry I want it to use the same route. But when I navigate to localhost:3000/test/math/geometry.test I want it to use a different route. I have used regex before just not sure how to combine it with the express params functionality.
EDIT: adeneo's idea will not work since I cannot chain my functions correctly using a check for a period. This is the point of regex, so that I check the url before I do the page logic.
Raul I'm afraid you have misunderstood the question. Let me try to state it more clearly.
I have a list of folders like this:
test
--folder1
----test1.js
----test2.js
----test3.js
--folder2
----folder2-1
----folder2-3
------test4.js
------test5.js
----test6.js
--folder3
The following urls should have one regex expression that captures them:
test/folder1
test/folder2
test/folder2/folder2-3
and another that only catches the following:
test/folder1/test1.js
test/folder2/folder2-3/test4.js
test/folder2/test6.js
Like I said, I have done regex, I just cannot figure out how to use the :paramName functionality of Express with it.
The order does matter in this case.
If you put first the exceptions yo will handled the path.
app.get('/test/math/geometry.test', function (req, res) {
res.send('catch it');
});
app.get('/test/:path*', function (req, res) {
res.send('the params are ' + JSON.stringify(req.params));
});
If you try this routes with for example ´/test/maths/dificults´ you can see in the end that req.params have something like:
{"0":"/maths/dificults","path":"maths"}
You can access to the raw param by position, in this case '0' because by name you have the params cut in the first '/'
EDIT
You can apply the same concept and use the real regular expression inside:
app.get(/\/test\/[^\.]*$/, function (req, res) {
res.send('catch it without dot');
});
app.get('/test/*', function (req, res) {
res.send('catch it with dot');
});
And you can use parentesis () to capture params in
req.params like //test/([^.]*)$/
Related
I have a simple route like the following:
app.get("/posts/:country?/:city?", function (req, res) {
res.redirect("/");
});
How may I skip country but only define city (when necessary), both of which are optional parameters? In other words, I would like to have undefined for country but a value for city.
Ideally, how could something like this /posts//paris be achieved, without having to do /posts/france/paris?
If that is not possible, what is the reasoning behind it?
You could simply send a request to the following url: /posts/1/Berlin
Basically any value you want and you're sure your country param cannot take. Then use an if to determine the case where the country is not sent.
In other words, whenever you send 1 for country, you know that in that case you don't get a country.
I actually found the solution on the official documentation here https://expressjs.com/en/guide/routing.html. It's not exactly as I initially thought it could be implemented, however it fulfils the requirement sufficiently.
app.get("/posts/country/:country?/city/:city?", function (req, res) {
res.redirect("/");
});
In my node.js server i havce a URL variable.
It is either in the form of "https://www.URL.com/USEFUL_PART/blabla", or "URL.com/USEFUL_PART/blabla".
From this, i want to extract only the 'USEFUL_PART' information.
How do i do that with Javascript?
I know there are two ways to do this, one with vanilla js and one with regular expressions.
I searched the web but i only found SO solutions to specific questions. Unfortunately, i coulnd't find a generic tutorial i could replicate or work out my solution.
Since you're using Express, you can specify the part of the URL you want as parameters, like so:
app.get('/:id/blabla', (req, res, next) => {
console.log(req.params); // Will be { id: 'some ID from the URL']
});
See also: https://expressjs.com/en/api.html#req.params
In Node.js you can use "URL"
https://nodejs.org/docs/latest/api/url.html
const myURL = new URL('https://example.org/abc/xyz?123');
console.log(myURL.pathname);
// Prints /abc/xyz
One way is to check whether the url starts with http or https, if not then manually add http, parse the url using the URL api, take the patname from parsed url, and get the desired part
let urlExtractor = (url) =>{
if(!/^https?:\/\//i.test(url)){
url = "http://" + url
}
let parsed = new URL(url)
return parsed.pathname.split('/')[1]
}
console.log(urlExtractor("https://www.URL.com/USEFUL_PART/blabla"))
console.log(urlExtractor("URL.com/USEFUL_PART/blabla"))
Hey if you are using express then you can do something like this
app.get('/users/:id/blabla',function(req, res, next){
console.log(req.params.id);
}
Another way is to use javascript replace and split function
str = str.replace("https://www.URL.com/", "");
str = str.split('/')[0];
In my nodejs and "express" application I have this:
app.get("/:page?", function (req, res) {
var pg = req.params.page;
which corresponds to localhost:123 or localhost:123/3.
However, I want to be able to get the current page the same way by req.params.page, but the url should be localhost:123 or localhost:123/?page=X.
How?
My first suggestion is that you do not define your endpoint with /:variable. This will then match any route you create that follows that pattern. You should instead use something like /pages/:page to get a specific page
Then, you should use the URL parameter functionality in Express to include a URL parameter.
Define your route like this:
app.get("/pages/:page", function (req, res) {
var pg = undefined;
if (req.query.page) {
pg = req.query.page;
}
}
You can then access the page in req.query.page if it exists and do whatever you want with that value.
So for example, you could submit a request with localhost/pages/123?page=3.
req.query.page would equal 3 and req.params.page would equal 123.
You should instead define your route without the ? and if you do a get operation, for example on localhost:123/3?this=that then the req.query.this will be populated with the value that
I am trying to create an app that will get a url using Express. This url is defined in the ?code= parameter, but I won't know the value of the string after code.
I've tried doing something like this:
app.get('?code=' + /(.*)/i, function(req, res) { /* ... */ });
And later something like this:
app.get(/\?code=(.*)/i, function(req, res) { /* ... */ });
But it never matches. I know to use .* to match any string via regex, but this isn't how. I was thinking of doing some kind of match expression, but I'm not sure what string to use match on.
It looks like you might be misunderstanding what get is expecting. Also, the regex string you are passing is just becoming a string, not doing you much good, but you don't need it anyways.
your app.get syntax should likely be something like this:
app.get('/myAwesomeURL/moreURL/:code', function(request, response) {
var valueForCode = request.params.code;
});
but if you are actually only trying to trigger a route based on the presence of the word code, then you can pass straight regex as the first parameter, and test for all kind of things:
app.get(/^(?![\w\/\:].*code$)/, function (request, response) {//stuff});
I have the following code in my Node/Express project
exports.getProductById = function(req, res){
db.get('product', req.params.id).then(function(res2){
res.render('product/get', {title:'Product', product:res2.body, categories: db.categories});
})
.fail(function (err) {
res.redirect('/');
})
}
This works but it seems like it could be a lot better, however, my lack of Javascript experience seems to be an issue. I would envision something like this...
var callback = function(res2){
res.render('product/get', {title:'Product', product:res2.body, categories: db.categories});
}
var errorCallback = function (err) {
res.redirect('/');
}
exports.getProductById = function(req, res){
db.get('product', req.params.id).then(callback)
.fail(errorCallback)
}
Of course the problem here is I have no idea how to pass the res object to the Callback. What is the best pattern for handling this type of scenario?
Hey I wrote the orchestrate.io client library for JavaScript, and your first run through is actually good. I think you'll find it easier to keep req and res within the getProductById function. If you wish to avoid clutter, you can write additional functions that handle the data, format it, etc. and return back those changes to getProductById. This will make it easier to keep track of what is going on.