Nodejs 调用路由时,变量如何传输

Nodejs 调用路由时,变量如何传输

在app.js中如果有var test=123;然后调用路由app.get(’/’,routes.index);那么,如何在routes.js中获得app.js中的test变量呢?因为test不是req的一部分,不能通过req[’ ‘]的形式访问啊。我试过app.get(’/’,routes.index,{test=123});也是不行的。

3 回复

当然可以!在Node.js中,如果你想在不同的模块之间传递变量,可以通过几种常见的方法来实现。下面是一个简单的例子,展示如何在app.js中定义一个变量,并在routes.js中使用它。

示例代码

app.js

const express = require('express');
const routes = require('./routes'); // 引入路由模块
const app = express();

// 定义一个变量
const test = 123;

// 将变量传递给路由模块
routes.setTest(test);

// 设置路由
app.get('/', routes.index);

app.listen(3000, () => {
    console.log('Server is running on port 3000');
});

routes.js

let testValue = null;

module.exports = {
    index: (req, res) => {
        if (testValue !== null) {
            res.send(`The value of test is: ${testValue}`);
        } else {
            res.send('The value of test has not been set.');
        }
    },
    setTest: (value) => {
        testValue = value;
    }
};

解释

  1. 定义变量:在app.js中定义了一个名为test的变量。
  2. 传递变量:通过调用routes.setTest(test)test变量传递给routes.js模块。
  3. 设置路由:将路由与index函数关联起来。
  4. 获取变量:在routes.js中定义一个变量testValue,并通过setTest方法将其设置为从app.js传递过来的值。
  5. 使用变量:在index函数中使用testValue变量,并将其返回给客户端。

这种方法使得变量可以在不同的模块之间共享和传递,同时保持了模块的独立性。希望这个例子能帮助你理解如何在Node.js中传递变量。


如下:

var test = 123;
app.get('/do', loadData, routes.index);
function loadData(req, res, next) {
    req.test = test;
    next();
}

然后在routes.index里就可以通过req.test取出值来了

在Node.js中,app.jsroutes.js 是两个独立的模块,它们之间的变量不能直接传递。但是,你可以通过几种方法来实现变量的传递:

方法一:将变量作为参数传递给路由函数

你可以在定义路由时将变量作为参数传递给路由处理函数。

app.js

var express = require('express');
var routes = require('./routes/index');

var app = express();
var test = 123;

// 将变量传递给路由处理函数
app.get('/', (req, res) => {
    routes.index(req, res, { test });
});

// 其他配置和中间件...

routes.js

module.exports.index = function(req, res, options) {
    // 在这里可以访问到 `test` 变量
    var testValue = options.test;
    res.send(`Test value is ${testValue}`);
};

方法二:使用全局变量

虽然不推荐在生产环境中使用全局变量,但在开发阶段,你也可以使用全局变量来传递数据。

app.js

var express = require('express');
var routes = require('./routes/index');

var app = express();
global.test = 123;  // 设置全局变量

app.get('/', routes.index);

// 其他配置和中间件...

routes.js

module.exports.index = function(req, res) {
    // 在这里可以通过 global.test 访问到变量
    var testValue = global.test;
    res.send(`Test value is ${testValue}`);
};

方法三:使用配置对象

你还可以创建一个配置对象,并将其传递给路由处理函数。

app.js

var express = require('express');
var routes = require('./routes/index');

var app = express();
var config = { test: 123 };

app.get('/', (req, res) => {
    routes.index(req, res, config);
});

// 其他配置和中间件...

routes.js

module.exports.index = function(req, res, config) {
    // 在这里可以访问到 `config.test`
    var testValue = config.test;
    res.send(`Test value is ${testValue}`);
};

以上三种方法都可以帮助你在不同的模块之间传递变量。选择哪种方法取决于你的具体需求和项目结构。

回到顶部