Reputation: 1429
I'm trying to add multiple query string values at the current url but i'm not understanding how to do it.
I'm using express
and Nodejs
.
I've created a route that can read the values
router.get('/posts', (req, res) => {
Post.find({}).populate('files').exec((err, posts) => {
if(err){
res.redirect('/');
console.log(err);
} else {
console.log(req.query)
res.render('home');
}
});
});
and in the home page i've set some links that add query values
<a href="?Value1=1">Value1</a>
<a href="?Value2=2">Value2</a>
<a href="?Value3=3">Value3</a>
but each time that i click one of them the url resets the query string and add the query value of the cicked link.
So how can i concatenate them?
Upvotes: 1
Views: 1519
Reputation: 568
Firstly, you have to store all query string inside a variable to use them later and secondly, you need to parse current query, concatenate it with the previously stored ones and regenerate final query.
Here is an example:
const qs = require('querystring')
let queries = {}
router.get('/posts', (req, res) => {
Post.find({}).populate('files').exec((err, posts) => {
if(err){
res.redirect('/');
console.log(err);
} else {
queries = Object.assign({}, queries, req.query)
// this line will log concatenated query
console.log(qs.stringify(queries))
res.render('home');
}
});
});
Note: Don't forget to install querystring module.
npm i querystring
Upvotes: 1
Reputation: 536
I have some confused with your question.
If you want your link will be /?Value1=1&value2=2&value3=3
, you can use :
//script.js
let oldUrl = window.localtion;
let newUrl = oldUrl + '&value2` //and the same with value3
$('yourElement').attr('href')= newUrl; //yourElement maybe id,name,...etc
I hope it can help you !
Upvotes: 1