Javascript Wildcards with Express - javascript

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});

Related

How to skip one of multiple optional route parameter in Node.js express

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("/");
});

Node.js - Extracting part of the URL

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];

How can I use "?param=X" in a route in NodeJS?

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

Express Javascript Regex to only allow strings without periods

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/([^.]*)$/

How to get Nice-Looking URLS - Node.JS

I have been looking around the web for a way to get the URL that is like:
example.com/games/game1 instead of example.com/games?id=game1
I have looked around the Node.JS website but I couldn't find anything that seemed to apply to my situation.
Any help is very appreciated. I have found an answer that did this using a .HTACCESS file, but I couldn't find a node.js alternative. The question/answer that I found was, creating nice looking URLs
Any help is very appreciated.
This URL example.com/games?id=game1 is passing the id as a GET parameter. To replace it with example.com/games/game1, you just have to come with a strategy on how to pass this id. This strategy is usually referred to node.js as routes, and, they are plenty of options on how to achieve your goal:
If you are using Express framework, you have built in ability to do stuff like this (based off TJ Holowaychuk's route separation examples):
app.get('/games/:id', games.view);
Then, in your game.js file:
exports.view = function(req, res){
console.log(req.params.id); //gives you game1
//...
};
- Another way to do it is to use something specific for routing (instead of a whole framework). Director comes to mind.
var viewGame = function(gameId) { console.log(gameId); };
var routes = {
'/games/:gameId': viewGame
};
You can list to all requests, then parse request.url to decide which page to render or whether to return a 404 / 302 or whatever you want to do. This is just a small example. You probably want to separate your routing from your logic:
var http = require("http");
http.createServer(function(request, response) {
var parts = request.url.split('/');
if(parts[0] === 'games'){
var id = parts[1];
// Check if valid id
// And render the correct page
}
}).listen(80);

Categories

Resources