Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do you send html with restify

Tags:

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>');
like image 918
MonkeyBonkey Avatar asked Jun 11 '12 00:06

MonkeyBonkey


People also ask

What is Restify server?

A restify server object is the main interface through which you will register routes and handlers for incoming requests.

What is Restify framework?

A Node. js web service framework optimized for building semantically correct RESTful web services ready for production use at scale. restify optimizes for introspection and performance, and is used in some of the largest Node. js deployments on Earth.


2 Answers

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();
like image 122
serg Avatar answered Oct 21 '22 01:10

serg


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;
        }
    }
});
like image 37
dlawrence Avatar answered Oct 21 '22 02:10

dlawrence