从一个路由到另一个路由传递对象数组 [英] Pass array of objects from route to route

查看:559
本文介绍了从一个路由到另一个路由传递对象数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Node.js和Express.js,并尝试将一组对象从路由传递到其他路由. 我试图通过QueryString,但是typeof表示它是一个对象,无法正常工作. 我应该以某种方式将其传递给/contacts,或者将QueryString的结果转换为对象数组并使用它.

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.

这是我尝试做的事情:

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.

推荐答案

另一种方法是使用app.locals. 基本上,它允许您在应用程序的生存期内存储一些变量. 对于路线,将出现req.app.locals.

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.

那如何使用它呢?

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);
})

(可在此处找到更多信息)

这篇关于从一个路由到另一个路由传递对象数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆