且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

“app.render"和“app.render"有什么区别?和“res.render"在 express.js 中?

更新时间:2023-11-26 15:49:22

以下是一些差异:

  1. 您只能在根级别res.render上调用app.render路由/中间件.

app.render 总是在回调函数中返回html ,而res.render仅当您将回调函数指定为第三个参数时才这样做.如果您在没有第三个参数/回调函数的情况下调用 res.render,则渲染的 html 将发送到客户端,状态代码为 200.

app.render always returns the html in the callback function, whereas res.render does so only when you've specified the callback function as your third parameter. If you call res.render without the third parameter/callback function the rendered html is sent to the client with a status code of 200.

看看下面的例子.

  • app.render

app.render('index', {title: 'res vs app render'}, function(err, html) {
    console.log(html)
});

// logs the following string (from default index.jade)
<!DOCTYPE html><html><head><title>res vs app render</title><link rel="stylesheet" href="/stylesheets/style.css"></head><body><h1>res vs app render</h1><p>Welcome to res vs app render</p></body></html>

  • res.render 不带第三个参数

  • res.render without third parameter

    app.get('/render', function(req, res) {
        res.render('index', {title: 'res vs app render'})
    })
    
    // also renders index.jade but sends it to the client 
    // with status 200 and content-type text/html on GET /render
    

  • res.render 带第三个参数

  • res.render with third parameter

    app.get('/render', function(req, res) {
        res.render('index', {title: 'res vs app render'}, function(err, html) {
            console.log(html);
            res.send('done');
        })
    })
    
    // logs the same as app.render and sends "done" to the client instead 
    // of the content of index.jade
    

  • res.render 使用 app.render 在内部渲染模板文件.

    res.render uses app.render internally to render template files.

    您可以使用 render 函数来创建 html 电子邮件.根据您的应用程序结构,您可能并不总是可以访问 app 对象.

    You can use the render functions to create html emails. Depending on your structure of your app, you might not always have acces to the app object.

    例如在外部路由中:

    app.js

    var routes = require('routes');
    
    app.get('/mail', function(req, res) {
        // app object is available -> app.render
    })
    
    app.get('/sendmail', routes.sendmail);
    

    routes.js

    exports.sendmail = function(req, res) {
        // can't use app.render -> therefore res.render
    }