Pass Array Of Objects From Route To Route
I'm using Node.js and Express.js and I tried to pass an array of objects from route to other route. I tried to pass through QueryString, but the typeof says that it is an object an
Solution 1:
You can use JSON.stringify.
app.get('/names', function(req, res) {
var arr = new Array();
arr.push({name: 'John'});
arr.push({name: 'Dani'});
res.redirect('/contacts?arr=' + JSON.stringify(arr));
})
app.get('/contacts', function(req, res) {
var arr = req.query.arr;
console.log(JSON.parse(arr));
})
Solution 2:
Another approach would be to use app.locals
.
Basically, it allows you to store some variables for the lifetime of the application.
For routes, there will be req.app.locals
.
So how to use it then?
app.get('/names', function(req, res) {
var arr = new Array();
arr.push({name: 'John'});
arr.push({name: 'Dani'});
req.app.locals.nameOfYourArr = arr;
res.redirect('/contacts');
})
app.get('/contacts', function(req, res) {
var arr = req.app.local.nameOfYourArr;
console.log(arr[0].name);
})
(More info can be found here)
Post a Comment for "Pass Array Of Objects From Route To Route"