newbie nodejs quest - 在路由/文件之间传递数据

时间:2016-11-20 14:26:22

标签: javascript node.js

我是node.js中的新手,我很头疼因为我无法获得如何在node.js中的文件/路由之间传递数据

我的文件结构看起来像这样(非常简单的流行结构):

ROUTES (folder)
--form.js
--test.js

VIEWS (folder)
--form.ejs
--test.ejs

index.js
package.json

index.js文件(标准快递应用文件):

var express = require('express');
var body_parser = require('body-parser');

var form = require('./routes/form.js');
var test = require('./routes/test.js');

var app = express();
app.set('view engine', 'ejs');
app.use(body_parser.urlencoded({extended:true}));

app.use('/', form);
app.use('/test', test);

var port = 3700;
var server_listen_on = app.listen(port, function()
{
    console.log('Server is listening on port: ' + port);
});

form.ejs文件:

<!DOCTYPE html>
<html>
<head>
<title>pole</title>

</head>
<body>

Hi! Put some web address here:</br>

<form action="/post" method="post">
    <input type="text" name="address">
    <input type="submit" value="ENTER OR CLICK HERE">
</form> 

</body>
</html>

test.ejs文件:

<!DOCTYPE html>
<html>
<head>
<title>test</title>

</head>
<body>

    The page you fill in:<br>
    <%= target %><br>
    Let us see how it looks like:<br>


</body>
</html>

form.js文件

var express = require('express');
var body_parser = require('body-parser');
var router = express.Router();

router.get('/', function(req, res, next)
{
    res.render('form'); // this is rendering our form - as a start page
});

router.post('/post', function(req, res, next)
{
    var data = req.body.address; // user fill the form (test.ejs file)
    res.render('test', {target : req.body.address}); // we grab the data that user put in the form and render test page that will show this data
    module.exports.page = data; // now I want to pass it to other js file - test.js
});





var page = function()
{
    console.log('just for test purpose');
};

module.exports = router; // right now module.exports is equal to router (express.router).
// How to pass some more data in it (like above function - page) - something like module.exports = page + router; So I could use page variable in other js file[?]

test.js文件:

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

var req_formjs = require('./form.js');

console.log(req_formjs.data); // undefined... [?] how to pass variables from form.js to test.js [?]

router.get('/', function (req, res, next)
{
    request.get(target, function (err, res, body) // putting target in here (as a url) isn't working... [?] how to pass variable from router.post in form.js to router.get in test.js [?]
    {
        if (!err && res.statusCode == 200)
        {
            res.render('test', {content : body}); // second render of test.ejs is not working [?]
        }
        else
        {
            console.log('error');
        }
    });
});

module.exports = router;

越简单(答案)越好。代码中有一些问题 - 为了更好地理解。如果有任何教程或类似的问题(我确实检查过,我找不到任何好的描述),请回答粘贴链接,谢谢。

编辑:让我们使用更简单的形式来更好地理解。问题是如何以最简单的模式将变量传递给其他js文件(没有任何路由只使用module.exports)。

index.js - 相同

form.js

var express = require('express');
var body_parser = require('body-parser');
var router = express.Router();

var preciousData = 'var precious_data - from form.js file';

module.exports =
{
    exportsPreciousData : preciousData,
    router : router
};

test.js

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

var requireFormjs = require('./form.js');//({exportsPreciousData : exportsPreciousData});


//console.log(requireFormjs.exportsPreciousData); // I guess console.log is faster then module.exports... but

router.get('/', function(req, res, next)
{
    res.render('welcome', {test : requireFormjs.exportsPreciousData});
});

// why this doesn't work - I need to use middleware function - could you provide simple working example?
//(I guessing that even if console.log print data after module.exports machinery I would still need middleware, right?)

module.exports = router;

welcome.ejs

<!DOCTYPE html>
<html>
<head>
<title>welcome</title>

</head>
<body>

<%= test %>

</body>
</html>

...为什么它没有工作(没有表达一切正常)?

1 个答案:

答案 0 :(得分:0)

你可以输出你想要的任何东西。如果你想通过路由器加上页面功能,你可以这样做:

module.exports = {
  router: router,
  page : page
};

相反,如果你想在所需的模块中注入一些东西,你就会暴露一个函数,例如:

module.exports = function(options){
   // do something with the options
   return router; // possibly modified by the options
};

// in your requiring file

var formRouter = require('./router')({key: 'value'});
app.use(formRouter);

**评论后编辑**

至于尝试在路由处理程序中间导出,正如您在此处所做的那样:

router.post('/post', function(req, res, next)
{
    var data = req.body.address; // user fill the form (test.ejs file)
    res.render('test', {target : req.body.address}); // we grab the data that user put in the form and render test page that will show this data
    module.exports.page = data; // now I want to pass it to other js file - test.js
});

这样做真的没有意义。首先,模块仅在正在运行的应用程序的生命周期中导出一次。它们本质上是一个Singleton,它在第一次require语句中首次实例化。因此,稍后导出数据意味着您只有在编写完成后才能拥有最后一篇文章的数据。此外,该处理程序可能会在您的应用程序中多次触发(每次发布时)。

如果您告诉我们您希望在每个帖子上导出该数据的原因,我可能会告诉您解决实际需求的最佳方法。