What's the difference between “app.render” and “res.render” in express.js?

前端 未结 3 612
我寻月下人不归
我寻月下人不归 2020-12-07 08:52

Docs for app.render:

Render a view with a callback responding with the rendered string. This is the app-level variant of res.render(), an

3条回答
  •  Happy的楠姐
    2020-12-07 09:38

    Here are some differences:

    1. You can call app.render on root level and res.render only inside a route/middleware.

    2. 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.

      Take a look at the following examples.

      • app.render

        app.render('index', {title: 'res vs app render'}, function(err, html) {
            console.log(html)
        });
        
        // logs the following string (from default index.jade)
        res vs app render

        res vs app render

        Welcome to res vs app 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 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
        
    3. res.render uses app.render internally to render template files.

    4. 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.

      For example inside an external route:

      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
      }
      

提交回复
热议问题