javascript - 如何将数据从 get 函数获取到 node.js 中同一个 js 文件中的另一个函数?
问题描述
我想从一个router.get()
函数中获取数据到位于同一个 JS 文件中的另一个函数。
我有一个数据发送到 get 方法:
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
现在我想title
在另一种方法中使用变量:
router.post('/', function(req, res) {
// I want to use the title variable in here
});
任何帮助,将不胜感激。
解决方案
您只需要更改变量的范围。但在扩展变量范围时要小心。即,您将在路由器回调之外设置标题,然后在内部引用它。此外,随着您的 Web 应用程序的增长,您可能会有许多不同的页面,每个页面都有自己的页面标题。
完成这项工作的简单方法是在路由处理程序之外初始化标题:
// 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]);
});
作为替代方案,expressJS 允许我们使用app.get()
和app.set()
方法。通常大多数 expressJS 应用程序都是这样开始的:
let app = express();
您可以像这样存储与应用程序关联的变量:
app.set('indexTitle', 'Express');
因此,在您的路由处理程序中,您可以像这样访问:
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'));
});
然而,更简单的方法可能是让前端跟踪所有页面标题,如果标题绝对是后端需要的,前端可以简单地将其发布在req.body
. 是的,可能有点矫枉过正,但它会消除服务器跟踪它的需要:
router.post('/', function(req, res) {
// Access your title here:
console.log(req.body.pageTitle);
});
推荐阅读
- sql-server - LIKE '%[9-15]%' (SQL Server)
- vue.js - 在 iView UI 表中显示/隐藏折叠行
- angular - 从多个数据源检索数据
- sql - 在 SQL Server 中创建枚举
- jquery - jquery tablesorter - 使用图像和 div 提取文本
- c# - 从 Gmail API 检索超过 100 个邮件 ID
- c++ - Is it possible to declare a template function with 'auto' return type as a friend of a class?
- html - How can I prevent screenreaders from reading the entire contents of a list item without pausing?
- ruby-on-rails - RabbitMQ with sidekiq
- scala - Scala cats and traverse syntax for Either - doesn't compile