How can I get the hexadecimal numbers from the base URL string - javascript

I am doing codes in node js express js But while working, I thought that if the hexadecimal number was taken from the base URL string, then my work would be easier.
I mean:
baseUrl: '/api/v1/movies/61b6e1c5503b122ff9436b14/seasons' (Get from req.baseUrl)
My base URL string is: '/api/v1/movies/61b6e1c5503b122ff9436b14/seasons'
I need just: 61b6e1c5503b122ff9436b14
I am currently using the javaScript replace() method but it does not seem to be very effective to me. I am especially interested to know any good method.
Thanks

Regexp would be useful unless you are looking for dynamic routes
This would get the code
let baseUrl = '/api/v1/movies/61b6e1c5503b122ff9436b14/seasons'
const hex = baseUrl.match(/movies\/(\w+)\/seasons/)[1]
console.log(hex.toUpperCase());

What you're looking for are called dynamic routes and in express you can do like this:
const express = require('express');
const app = express();
app.get('/api/v1/movies/:hexid/seasons', (req,res) => {
console.log(req.params.hexid);
})
You can find more info in their docs ( search for :bookId )

You can use req.params to map the route parameters in ExpressJS
app.get('/api/v1/movies/:hashid/seasons', function (req, res) {
console.log(req.params.hashid)
})

Related

Get req params in client Javascript

Say I have a string like
http://somerandomwebsite.com/345345/465645456546
This string matches the pattern
http://somerandomwebsite.com/:userId/:gameId
From the above string, how do I extract the userId and gameId values no matter their length(so not substring)
I know in ExpressJS you can do
app.get("/:userId/:gameId", (req, res) => {
var userId = req.params.userId
var gameId = req.params.gameId
})
But I need this to work in client side Javascript
Is there any way to do this?
The URL API is a safe and modern method that works server and client side:
location.pathname can be used if it is the url of the page you are on
link.pathname can be used for link objects
Say I have a string - then you need to make it a URL first
const [_,userID, gameID] = new URL("http://somerandomwebsite.com/345345/465645456546")
.pathname.split("/");
console.log(userID,gameID);
You can use window.location.pathname to get the path name of a url.
window.location.pathname.split('/')

Specific URL path

I'm looking for a method to catch these urls:
https://my.server.com/subsite
https://my.server.com/subsite.html
... but not these:
https://my.server.com/otherpath/subsite
https://my.server.com/other/path/subsite
What I got so far is this code - but obviously I'm also catching the urls I do not want to get (from above):
var express = require('express');
let app = express();
app.get(/\/subsite(?:\.html)?$/, function(req, res) {
})
I tried to fix my code by inserting com before the regex but this does not seems to be a working solution: /.*com\/subsite(?:\.html)?$/.
How can I get around this issue?
This worked for me.
app.get(/.*com\/subsite(?:\.html)?$/, function(req, res) {
})
Here is where i tested it: https://regex101.com/r/42lhKg/1
You don't need to use a Reg Ex object, this will work fine:
app.get("/subsite(.html)?", function(req, res) {
/*...*/
})
Matches any path beginning with "subsite" and with possibility of a .html
Your Regex is missing a the constraint to make subsite appear only in the begging ^:
/^\/subsite(?:\.html)?$/
witch is the same as using just the string:
"/subsite(.html)?"
that I mentioned in the other answer.
Don't forget that in express you only care about the path and query part of the url.

how to pass a url as a "url parameter" in express?

In my express app I have a router listening to api/shorten/:
router.get('api/shorten/:longUrl', function(req, res, next) {
console.log(req.params.longUrl);
}
When I use something like:
http://localhost:3000/api/shorten/www.udemy.com
I get www.udemy.com which is what I expect.
But when I use:
http://localhost:3000/api/shorten/http://www.udemy.com
I get a 404 error.
I want to get http://www.udemy.com when I access req.params.parameter.
I'm not sure if you're still looking for a solution to this problem. Perhaps just in case someone else is trying to figure out the same thing, this is a simple solution to your problem:
app.get('/new/*', function(req, res) {
// Grab params that are attached on the end of the /new/ route
var url = req.params[0];
This way you don't have to sweat about any forward slashes being mistaken for routes or directories, it will grab everything after /new/.
You need to use encodeURIComponent in the client, and decodeURIComponent in the express server, this will encode all the not allowed characters from the url parameter like : and /
You need to escape as so:
escape("http://www.google.com")
Which returns:
"http%3A//www.google.com"
I just want to add that if you pass another params like ?param=some_param into your "url paramter" it will not show up in req.params[0].
Instead you can just use req.url property.

How to use parameters containing a slash character?

My MongoDB keys in person collection are like this:
TWITTER/12345678
GOOGLE/34567890
TWITTER/45678901
...
I define getPersonByKey route this way:
router.route('/getPersonByKey/:providerKey/:personKey').
get(function(req, res) { // get person by key
var key = req.params.providerKey + '/' + req.params.personKey;
// ...
}
);
Of course I'd prefer to be able to write something like this:
router.route('/getPersonByKey/:key').
get(function(req, res) { // get person by key
var key = req.params.key;
// ...
}
);
But this doesn't work, since GET http://localhost/getPersonByKey/TWITTER/12345678 of course results in a 404, since the parameter with the slash is interpreted as two distinct parameters...
Any idea?
Express internally uses path-to-regexp to do path matching.
As explained in the documentation, you can use a "Custom Match Parameter" by adding a regular expression wrapped in parenthesis after the parameter itself.
You can use the following path to get the result you need:
router.route('/getPersonByKey/:key([^/]+/[^/]+)').
get(function(req, res) { // get person by key
var key = req.params.key;
// ...
}
);
You can test and validate this or any other route here.
You can use this if your parameters has containing slashes in it
app.get('/getPersonByKey/:key(*)', function(req, res) { ... })
It works for me (at least in Express 4). In my case, I used parameters like ABC1/12345/6789(10).
Hopefully this useful.
app.get('/getPersonByKey/:key(*)', function(req, res) { ... })
This isn't working for me.
Swagger-ui will encode the path var before using it.
e.g. article/2159 will become article%2F2159.
When going directly with curl, it will not get encoded. the slash will remain a slash instead of %2F. And then the route is not matched.
Update: I'm on fastify. On express 4.X this works correctly.

How to read parameters from URL in a specific way with express JS

I created a server with the express package, and I'm trying to read in a specific way the parameters from the URL.
The URL goes like this: http://127.0.0.1:8080/screen=3 (no '?' as the sign for parameters).
I need to save the number of the screen in a variable.
I tried this:
var express = require('express');
var app = express();
app.get('/screen:sceenNum', function (req, res) {
var temp = req.sceenNum;
res.send(temp); //for checking on the browser
});
I also tried this, but he must get '?' in the URL:
app.get('/', function(req, res) {
var screenNum = req.param('screen');
res.send(screenNum);
});
Can anyone please have a solution?
Thank you
You can access route/url parameters with the req.params object.
So a route like /screen:screenNum would accept urls like /screen3 and you would access 3 via req.params.screenNum.
Similarly, if you want to use the equals, just add that: /screen=:screenNum and the number is accessed the same.

Categories