简体   繁体   English

如何使用Node.js和Express以块的形式发送HTML?

[英]How do I send HTML in chunks using Node.js and Express?

I want to send the <head> containing stylesheets before processing the rest of the page. 我想在处理页面的其余部分之前发送包含样式表的<head> In PHP, I could use ob_flush() . 在PHP中,我可以使用ob_flush()

I tried doing something like this: 我尝试过这样的事情:

app.set('view engine','ejs');

app.get('*',function(req,res){
  res.writeHead(200,{'Content-Type':'text/html'});
  res.write('<!doctype...<link rel=stylesheet...');

  doDBStuff()
    .then(function(data){
      res.render('index',{...}); // uses EJS for templating
    });
});

However, the res.render() part does not get sent. 但是, res.render()部分不会被发送。 Is there a built-in way to send chunked data? 是否有内置的方式来发送分块数据?

One way to do it would be to manually load the EJS files and manually process them. 一种方法是手动加载EJS文件并手动处理它们。 I would also have to manually send the appropriate headers. 我还必须手动发送相应的标头。 I prefer a build-in method if it exists. 如果存在,我更喜欢内置方法。

Here's a simple PoC that does what you want: 这是一个简单的PoC,可以满足您的需求:

var express = require('express');
var app     = express();
var server  = app.listen(3000);

app.set('views', 'views');
app.set('view engine', 'ejs');

app.get('/', function (req, res, next) {
  res.write('<!-- prefix -->');
  setTimeout(function() {
    res.render('index', { ... }, function(err, html) {
      // TODO: handle errors
      res.end(html);
    });
  }, 1000);
});

Note that it uses the "callback variant" of res.render() , which can be used to just render a template without sending back a response (if you don't do it this way, res.render() will generate an error). 请注意,它使用res.render()的“回调变体”,它可用于仅渲染模板而不发回响应(如果不这样做, res.render()将生成错误)。 Alternatively, you can use app.render() which does the same. 或者,您可以使用app.render()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM