我有一个Dust.js模板,并希望将其用作异步模式(如此流)以加载我的东西。 效果很好,但是当我添加use(helmet())时,它不再显示为html,而是显示为纯文本
我尝试使用灰尘。流,霍夫曼,阿达罗。没有任何效果,引入了第二个头盔,它不起作用。
霍夫曼
hoffman = require('hoffman'),
express = require('express'),
helmet = require('helmet'),
request = require('request');
var app = express();
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'dust');
app.engine('dust', hoffman.__express());
app.use(helmet());
// This is the important part-- it adds res.stream()
app.use(hoffman.stream);
app.get('/', function (req, res) {
res.stream("hello", {
"async": function(chunk, context, bodies, params) {
return chunk.map(function(chunk) {
// Introducting an artificial delay to make streaming more apparent
setTimeout(function() {
request('http://www.dustjs.com/')
.on('data', chunk.write.bind(chunk))
.on('end', chunk.end.bind(chunk));
}, 3000);
});
}
});
});
const port = process.env.PORT | 3007;
app.listen(port, function () {
console.log(`Visit http://localhost:${port} to see streaming!`);
});
灰尘流:
var fs = require('fs'),
path = require('path'),
express = require('express'),
request = require('request'),
helmet = require('helmet'),
dust = require('dustjs-linkedin');
dust.config.whitespace = true;
dust.config.cache = false;
// Define a custom `onLoad` function to tell Dust how to load templates
dust.onLoad = function(tmpl, cb) {
fs.readFile(path.join('./views', path.relative('/', path.resolve('/', tmpl + '.dust'))),
{ encoding: 'utf8' }, cb);
};
var app = express();
app.use(helmet());
app.get('/streaming', function(req, res) {
dust.stream('hello', {
"async": request('http://www.dustjs.com/')
}).pipe(res)
.on('end', function() {
console.log('Done streaming!');
});
});
app.get('/rendering', function(req, res) {
dust.render('hello', {
"async": request('http://www.dustjs.com/')
}, function(err, out) {
res.send(out);
console.log('Done rendering!');
});
});
const port = process.env.PORT | 3002;
app.listen(port, function () {
console.log(`Visit http://localhost:${port} to see streaming!`);
});
不使用头盔时,呈现html,添加头盔时,不呈现任何渲染,我将html页面视为文本
答案 0 :(得分:0)
好,所以灰尘可以很好地利用异步。
我所缺少的是:
res.setHeader('Content-Type', 'text/html; charset=utf-8');
现在它可以与头盔一起使用!