【问题标题】:New to express, where do I start?新的表达,我从哪里开始?
【发布时间】:2014-01-20 23:08:27
【问题描述】:

我正在学习 node/express。我已经购买了几本书并遵循了一些在线指南,我想开始修补,但我不知道在哪里为我的路线添加逻辑。 我使用 express 命令行工具创建了一个基本应用程序。我现在在我的 app.js 中定义了两条路由

app.get('/', routes.index);
app.get('/users', user.list);

我看到了翡翠模板,我认为我完全有能力通过翡翠/手写笔提供普通的旧 html。但我想添加逻辑,但我不知道在哪里做。它是否像php一样工作,就像我将逻辑添加到jade html文件中一样,还是我以某种方式将它放在app.js中。

我在一个例子中看到了如何在jade中引用一个变量,但是我想在页面显示时运行代码(服务器端,如php)。

我经常引用 php,因为它是我唯一熟悉的语言。

【问题讨论】:

    标签: node.js express


    【解决方案1】:

    一种常见的模式是将逻辑分离为您从路由中调用的函数,您可以将它们放在单独的文件中

    var express = require('express');
    var app = express();
    require('http').createServer(app).listen(3000);
    app.use(express.logger());
    app.use(express.bodyParser());
    app.use(app.router);
    app.set('views', __dirname + '/templates');
    app.set('view engine', 'jade');
    
    var myLib = require('lib/myLib.js');
    // myLib will contain: module.exports = { foo:function(req, arg, callback){ ... } };
    
    app.get('/', function(req, res){
      myLib.foo(req, 'hello', function(err, result){
        // this is passed into foo as `callback` and generally is called from foo
        if(err){ return res.send(500) };
        res.send(200, 'Foo was ' + result);
      });
    });
    
    // edit - ways to structure this with app.render for a jade template
    app.get('/jade1', function(req, res){
      myLib.bar(req, res); 
      // it is now myLib.bar's responsibility to send a response with the `res` object,
      // either with res.end, res.send, res.render, res.redirect or whatever
    });
    
    // my preferred way: (i usually try to keep my logic separated from req/res)
    app.get('jade2', function(req, res){
      var username = req.body.username;
      myLib.getUser(username, function(err, result){
        if(err){ return res.send(500) };
        res.locals.foobar = 'hello world';     
        // res.locals.x is equivalent to passing {x:_} inline to render as below: 
        res.render('jade2', {user: result});
      });
    });
    

    【讨论】:

    • 您也可以将整个路由功能放在一个单独的文件中,并从 app.js 中请求它,从而设置您的路由。我认为这是默认快速设置中的行为,我也认为它很好地展示了in the express examples
    • 也可以直接在你的路由中加入逻辑。一些缺点是,如果您想从其他地方调用该函数,它的可重用性会降低,并且会弄乱您的路线。
    • 你如何将它与jade生成的html集成?例如,来自快速工具生成的应用程序的默认索引页面。顺便说一句,答案很棒,谢谢。
    • 我个人只是从 app.js 中删除 index.js 页面和对其的引用,并使用我自己认为合适的文件结构。如果你想使用玉,你会打电话给res.render,我会用两种可能的方式来编辑
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-13
    • 1970-01-01
    • 2011-08-12
    • 1970-01-01
    • 2010-10-12
    • 1970-01-01
    相关资源
    最近更新 更多