how do you send html with restify
Asked Answered
T

4

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>');
Taboo answered 11/6, 2012 at 0:29 Comment(0)
O
30

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();
Olette answered 30/3, 2013 at 20:4 Comment(3)
Does this not need to end with a call to next() ?Nickelson
This won't work if gzip encoding is used. It's better to use a custom response formatter and use res.send so the correct content-length is calculated.Valiancy
Nice. Thanks, I'm using Restify (Expressjs based on) alternative, and it works.Deliberative
V
13

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;
        }
    }
});
Viand answered 21/6, 2012 at 0:8 Comment(1)
FWMI. You can re-assign the original formatter using restify's library. Replace line 3 with: 'application/json': require('restify/lib/formatters/json')Ikhnaton
B
12

Another option is to call

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

Instead of

res.send('<html><body>hello</body></html>');
Brister answered 14/6, 2015 at 18:27 Comment(0)
A
4

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)
    }
  }
})
Abridgment answered 26/1, 2017 at 16:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.