简体   繁体   English

在 Node.js 中使用 require 传递对象和变量

[英]Passing objects and variables using `require` in `Node.js`

I am working on moving routing methods from app.js to separate files.我正在将路由方法从app.js移动到单独的文件。

I managed to do it using (in app.js ):我设法使用(在app.js )做到了:

var userRoutes = require('./serverRoutes/userRoutes');
app.use('/userRoutes', userRoutes);
app.post('/user/login', userRoutes);

I can see that routing is being done.我可以看到路由正在完成。

I have some variables in my app.js like:我的app.js有一些变量,例如:
- tokens array - tokens数组
- jwtSecretKey string - jwtSecretKey字符串
- jwt encryption module - jwt加密模块
- User which is mongoose schema - 猫鼬模式的User

I would like to pass them and make them usable by routing methods inside userRoutes.js file.我想通过userRoutes.js文件中的路由方法传递它们并使它们可用。

I do not know how to do it.我不知道怎么做。

Another question.另一个问题。

I also have some 'helper' type methods I would like to use in different 'routing' files.我还有一些“辅助”类型的方法,我想在不同的“路由”文件中使用。

I do not know how to pass them either.我也不知道如何通过它们。

This is how I deal with 'routing' files:这就是我处理“路由”文件的方式:

var express = require('express');
var router = express.Router();

router.post('/user/login', function (request, response) {
    var email = request.body.email;
    var password = request.body.password;

    User.findOne({ email: email, password: password },
        function (err, user) {
            if (err)
                response.send(err);

            if (user) {
                var expires = new Date();

                expires.setDate((new Date()).getDate() + 5);

                var token = jwt.encode({
                    email: email,
                    expires: expires
                }, jwtTokenSecret);

                tokens.push(token);
                response.send(200, { access_token: token });
            } else {
                response.send(401, { message: "User not found" });

            }
        });
});

module.exports = router;  

Thank you :-)谢谢 :-)

I am unsure what the "resolve" part of your title has to do with your question, but I can answer the rest of what you discuss in your question.我不确定您标题中的“解决”部分与您的问题有什么关系,但我可以回答您在问题中讨论的其余部分。

I have some variables in my app.js... I would like to pass them and make them usable by routing methods inside userRoutes.js file.我的 app.js 中有一些变量......我想传递它们并通过 userRoutes.js 文件中的路由方法使它们可用。

The usual way to share some settings with another module is to pass them to that module in a module constructor or a module method:与另一个模块共享某些设置的常用方法是在模块构造函数或模块方法中将它们传递给该模块:

var userRoutes = require('./serverRoutes/userRoutes')({
    tokens: tokens, 
    jwtSecretKey: jwtSecretKey, 
    jwt: jwt, 
    User: User
});

Then, inside that userRoutes module:然后,在 userRoutes 模块中:

var express = require('express');
var router = express.Router();
var jwtSecretKey, jwt, User, tokens;

router.post('/user/login', function (request, response) {
    var email = request.body.email;
    var password = request.body.password;

    User.findOne({ email: email, password: password },
        function (err, user) {
            if (err)
                response.send(err);

            if (user) {
                var expires = new Date();

                expires.setDate((new Date()).getDate() + 5);

                var token = jwt.encode({
                    email: email,
                    expires: expires
                }, jwtSecretKey);

                tokens.push(token);
                response.send(200, { access_token: token });
            } else {
                response.send(401, { message: "User not found" });

            }
        });
});

// define module constructor
module.exports = function(options) {
    // save data shared from parent module
    jwtSecretKey = options.jwtSecretKey;
    jwt = options.jwt;
    User = options.User;
    tokens = options.tokens;
    return router;
};  

I also have some 'helper' type methods I would like to use in different 'routing' files.我还有一些“辅助”类型的方法,我想在不同的“路由”文件中使用。 I do not know how to pass them either.我也不知道如何通过它们。

The usual way to share some common help functions is to put them in their own module and then you just require() in that module in any other module that you need to use them.共享一些常见的帮助函数的通常方法是将它们放在它们自己的模块中,然后在该模块中的任何其他模块中使用require()来使用它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM