问题
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 and it doesn't work properly.
I should either pass it to /contacts
in another way somehow, or convert the result of the QueryString to an array of object and use it.
Here is what I tried to do:
app.get('/names', function(req, res) {
var arr = new Array();
arr.push({name: 'John'});
arr.push({name: 'Dani'});
res.redirect('/contacts?arr=' + arr);
})
app.get('/contacts', function(req, res) {
var arr = req.query.arr;
console.log(arr[0].name);
})
Hope you can help, Thank you.
回答1:
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)
回答2:
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));
})
来源:https://stackoverflow.com/questions/44745133/pass-array-of-objects-from-route-to-route