Pass array of objects from route to route

元气小坏坏 提交于 2020-08-09 08:49:33

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!