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=¶m2=
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
Related
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
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('/')
Hey guys just started with nodejs and express so i came up with the situation where i want to send my data to my GET req from my POST req.Here is the code below for you to understand
app.post('/run-time',(req,res)=>{
const stoptime=req.body.stop
const plannedtime=req.body.planned
const runtime=plannedtime-stoptime
res.redirect('/run-time')
})
this is my POST req where i fetched the values from the form and then calculated the 'runtime' now then i have to redirect to specific GET route
app.get('/run-time',(req,res)=>{
})
so what i want is send the 'runtime' variable calulated in my POST req to my GET req here ..how can i do this ?
I've never been use that way But I think you can use querystring
querystring can contains data in url.
app.post('/run-time',(req,res)=>{
const stoptime=req.body.stop
const plannedtime=req.body.planned
const runtime=plannedtime-stoptime
res.redirect(`/run-time?runtime={runtime}`);
})
app.get('/run-time',(req,res)=>{
var runtime = req.query.runtime;
//~
})
I think that way can be your solution.
But you have to change your code because It is not used like this.
Maybe many solution is.
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.
I'm trying to use Postman to send a GET http request which contains a parameter which is dynamically generated by taking the full request query string (everything to the right of the question mark in the URL, after URL encoding), concatenating a previously assigned shared secret key, and then performing a SHA-1 hash of the resulting string.
I would use a Pre-request Script to achieve this.
Thank you.
I actually found a solution and would like to share it.
var params = [
["client_id", "222"]
,["account_id", ""]
];
// Build the request body string from the Postman request.data object
var requestBody = "";
var firstpass = true;
for(var i=0;i < params.length; i++) {
if(!firstpass){
requestBody += "&";
}
requestBody += params[i][0] + "=" + params[i][1];
firstpass = false;
postman.setGlobalVariable(params[i][0], params[i][1]);
}
requestBody += postman.getEnvironmentVariable("sharedSecretKey");
postman.setGlobalVariable("requestBody", requestBody);
var mac = "";
if(requestBody){
// SHA1 hash
mac = CryptoJS.SHA1(requestBody);
}
postman.setGlobalVariable("mac", mac);
Then I just need to set the parameters in the URL :
{{baseUrl}}/get?client_id={{client_id}}&account_id={{account_id}}&mac={{mac}}
where {{baseUrl}} is an environment variable
and {{client_id}}, {{account_id}} are global variables
Hope it can be helpful to someone.
Thank you.
Inspired by this answer, I used the following Postman pre-request script to create a SHA1 hash of a request.
Note that request.data is an implied variable and the CryptoJS library are provided by the Postman Sandbox for pre-request scripts.
const hash = CryptoJS.HmacSHA1(request.data, 'yourSecret').toString();
pm.globals.set('hash', hash);
You can now reference the hash value as a postman global variable using {{hash}} syntax.
Creating X-Hub-Signature Header like GitHub API Webhook Requests
My purpose in all this was to simulate the X-Hub-Signature header provided by the GitHub Webhooks API because my web service validates all webhook payloads to match the signature. So for me to test my web service, I also needed postman to generate a valid signature header.
Here's an adaptation of the above code snippet for generating the X-Hub-Signature request header value.
In GitHub, I set a webhook secret for my GitHub App.
In Postman, I created an environment and added the key=value pair GITHUB_WEBHOOK_SECRET with the value I specified when I created my GitHub App.
In Postman, I used the following pre-request script. It set the computed hash as a global variable.
const hash = CryptoJS.HmacSHA1(
request.data,
pm.environment.get('GITHUB_WEBHOOK_SECRET')
).toString();
pm.globals.set('X-HUB-SIGNATURE', 'sha1=' + hash);
In Postman, I reference the global hash variable as a header in my requests, just like the GitHub Webhooks API will.