Dust.js and helmet - not rendering HTML

142 views Asked by At

I have a Dust.js template and want to use it as async mode (so stream), to load my stuff. It works very well, but when I add use(helmet()) it does not show as html anymore, just as plain text

I tried using dust.stream, tried hoffman, tried adaro. nothing works, the second helmet is introduced, it does not work.

hoffman

    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!`);
});

Dust.stream:

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!`);
});

When not using helmet, the html is rendered, when adding helmet, no rendering is done, and I see the html page as text

1

There are 1 answers

0
Ilan On

Ok, so dust does a nice job with async.

The bit I was missing was:

res.setHeader('Content-Type', 'text/html; charset=utf-8');

and now it works with helmet!