21

I want to send plain html instead of a json response for one of my routes in restify. I tried setting the contentType and header property of the response but it doesn't seem to set the contentType in the header (the browser tries to download the file rather than render it).

res.contentType = 'text/html';
res.header('Content-Type','text/html');
return res.send('<html><body>hello</body></html>');
Ivan Krechetov
  • 18,802
  • 8
  • 49
  • 60
MonkeyBonkey
  • 46,433
  • 78
  • 254
  • 460

4 Answers4

29

Quick way to manipulate headers without changing formatters for the whole server:

A restify response object has all the "raw" methods of a node ServerResponse on it as well.

var body = '<html><body>hello</body></html>';
res.writeHead(200, {
  'Content-Length': Buffer.byteLength(body),
  'Content-Type': 'text/html'
});
res.write(body);
res.end();
serg
  • 109,619
  • 77
  • 317
  • 330
12

If you've overwritten the formatters in the restify configuration, you'll have to make sure you have a formatter for text/html. So, this is an example of a configuration that will send json and jsonp-style or html depending on the contentType specified on the response object (res):

var server = restify.createServer({
    formatters: {
        'application/json': function(req, res, body){
            if(req.params.callback){
                var callbackFunctionName = req.params.callback.replace(/[^A-Za-z0-9_\.]/g, '');
                return callbackFunctionName + "(" + JSON.stringify(body) + ");";
            } else {
                return JSON.stringify(body);
            }
        },
        'text/html': function(req, res, body){
            return body;
        }
    }
});
dlawrence
  • 1,645
  • 12
  • 13
  • 1
    FWMI. You can re-assign the original formatter using restify's library. Replace line 3 with: `'application/json': require('restify/lib/formatters/json')` – Alwin Kesler Jan 11 '18 at 02:56
12

Another option is to call

res.end('<html><body>hello</body></html>');

Instead of

res.send('<html><body>hello</body></html>');
Eran Boudjnah
  • 1,228
  • 20
  • 22
3

It seems like the behaviour @dlawrence describes in his answer has changed since when the answer was posted. The way it works now (at least in Restify 4.x) is:

const app = restify.createServer(
  {
    formatters: {
      'text/html': function (req, res, body, cb) {
        cb(null, body)
    }
  }
})
Stefano
  • 2,056
  • 2
  • 15
  • 13