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>');
A restify server object is the main interface through which you will register routes and handlers for incoming requests.
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.
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();
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;
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With