Get req params in client Javascript - 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('/')

Related

Express JS url parameter variable issue

I have this user route
const express = require('express');
const router = express.Router();
const {
GetAll,
} = require('../areas/directory/controllers/usercontroller');
router.route('/getall?:username&:email').get(GetAll);
module.exports = router;
When I try to access the url in Postman like this: http://localhost:5000/api/user/getall?username=nameone&email=emailone
I get this error: Cannot GET /api/user/getall
But, if I change it to
router.route('/getall/:username&:email').get(GetAll);
and access the url in Postman like this: http://localhost:5000/api/user/getall/username=nameone&email=emailone
it works.
On the other hand, even if it works, I am unable to get the value of my variable.
var username = req.params.username;
will return username=nameone instead.
For http://localhost:5000/api/user/getall?username=nameone&email=emailone to work, you should change
router.route('/getall?:username&:email').get(GetAll);
to
"router.route('/getall').get(GetAll);"
and use req.query.username to access the value of username query parameter and req.query.email to access the value of email query parameter.
After making these changes, you can call http://localhost:5000/api/user/getall?username=nameone&email=emailone in Postman, you will be able to see the value of username and email in your code.
This is because you need not have to specify the query parameters in the path, like ?:username in router.route('getall').
Edit: adding few more details about path and query
Please see the top 2 solutions for this question to learn more about path and query and why you should change your code to the way I mentioned above : here is the link.
Reason for the error...
Actually the thing what you are trying to do is called query passing in the rest api..
But you are trying to access them like params
sollution 💖
follow the steps to access the queries
**To pass the data using ? in the api request should be like this you can have multiple query objects
http://localhost:5000/getall?email='email'&&password='password'
Access the query in express app like this
app.post('/getall', (req, res) => {
const {
email,
password
} = req.query
return res.status(200).json({
email,
password
})
})
The req.query contains the data you trying to pass throw ? and then query properties
Response of above code would be like this
{
"email": "'email'",
"password": "'password'"
}
You should not give query parameters in URL. So, for express the url must be just /getall and in your code you access those variables using req.params.whatever_query_parameter

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

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

Firebase Functions Express : How to get URL params with paths

I have a url in the form www.a.com/users/uid, I want to get uid.
Assume a function :
exports.smartlink = functions.https.onRequest((req, res) =>
Doing req.params returns an empty array, whereas req.query.uid when the url contains query strings works.
If your URL is "www.a.com/users/uid", "uid" will be part of req.path. You can split that on '/' to get the uid as the last element of the array returned by split.
You can only use req.params with Cloud Functions for Firebase when you're exporting an entire Express app that defines a router that uses a placeholder for the element in the path you want to extract.
Alternatively, you can use express in firebase. and use req.param to get the value.

Number of parameters sent via URL in nodeJS

I need to find how many parameters sent in an URL.
How can I determine the number of parameters sent via URL in nodeJS?
use req.query
if Your URL is like localhost:3000?param1=&param2=
var params = req.query;
van length = Object.keys(params).length;
the length is 2.
If using express framework
req.params // can be used
See the documentation here

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