[英]How can I get data from a get function to another function in the same js file in node.js?
I want to get data out of a router.get()
function to another function located in the same JS file. 我想从
router.get()
函数中获取数据到位于同一JS文件中的另一个函数。
I have a data sent to a get method: 我有一个发送到get方法的数据:
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
Now I want to use title
variable in another method: 现在我想在另一个方法中使用
title
变量:
router.post('/', function(req, res) {
// I want to use the title variable in here
});
Any help would be appreciated. 任何帮助,将不胜感激。
You just need to change the scope of the variable. 您只需要更改变量的范围。 Be careful though when expanding the scope of variables.
在扩展变量范围时要小心。 Ie, you would set the title outside of your router callbacks, and then reference it inside.
即,您可以在路由器回调之外设置标题,然后在里面引用它。 Also, as your web app grows, it's possible you'll have many different pages, each with their own page titles.
此外,随着您的网络应用程序的增长,您可能会拥有许多不同的页面,每个页面都有自己的页面标题。
The easy way to make this work is to initialize the title outside the route handler: 使这项工作的简单方法是在路由处理程序之外初始化标题:
// Here, I'm using Object.freeze, assuming you want the map to be
// immutable (i.e., not accidentally changed by other parts of the code)
// (const titles = { ... } won't achieve it)
let titles = Object.freeze({ /* Formatted as a "route" --> "title" map */
index: 'Express'
});
router.get('/', function(req, res, next) {
const routeName = 'index'
res.render(routeName, { title: titles[routeName] });
});
router.post('/', function(req, res) {
const routeName = 'index'
// Access your title here:
console.log(titles[routeName]);
});
As an alternative, expressJS allows us to use app.get()
and app.set()
methods. 作为替代方案,expressJS允许我们使用
app.get()
和app.set()
方法。 Usually most expressJS apps start out like this: 通常,大多数expressJS应用程序都是这样开头的:
let app = express();
You can stash variables associated with the app like this: 您可以存储与应用程序关联的变量,如下所示:
app.set('indexTitle', 'Express');
So that way in your route handler, you can access like this: 这样在您的路由处理程序中,您可以像这样访问:
router.get('/', function(req, res, next) {
res.render(routeName, { title: app.get('indexTitle') });
});
router.post('/', function(req, res) {
// Access your title here:
console.log(app.get('indexTitle'));
});
Yet, an even easier approach may be to let the front-end keep track of all the page titles, and, if the title is absolutely something the back-end needs, the front-end can simply post that in the req.body
. 然而,一个更简单的方法可能是让前端跟踪所有页面标题,如果标题绝对是后端需要的东西,前端可以简单地在
req.body
。 Yes, might be overkill, but it would eliminate the need for the server to keep track of it: 是的,可能是矫枉过正,但它将消除服务器跟踪它的需要:
router.post('/', function(req, res) {
// Access your title here:
console.log(req.body.pageTitle);
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.