What is the purpose of the res.render callback argument in Express 4.0 in Node.js?

给你一囗甜甜゛ 提交于 2019-12-10 22:45:22

问题


What is the purpose of the res.render callback argument?

In which case would one want to use such a callback argument, since a template is already assigned as the first argument?

Here's the code from the documentation:

// send the rendered view to the client
res.render('index');

// if a callback is specified, the rendered HTML string has to be sent explicitly
res.render('index', function(err, html) {
  res.send(html);
});

// pass a local variable to the view
res.render('user', { name: 'Tobi' }, function(err, html) {
  // ...
});

I understand the purpose of the first two arguments, but not the last.


回答1:


With the callback, you can intercept the rendered template before sending it on. You might want to minify it or otherwise modify it before sending to the client.

From the documentation:

If provided, the method returns both the possible error and rendered string, but does not perform an automated response.



来源:https://stackoverflow.com/questions/44379563/what-is-the-purpose-of-the-res-render-callback-argument-in-express-4-0-in-node-j

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!