你怎么发送HTML与restify

我想发送一个简单的html而不是一个JSON响应为我的路线之一restify。 我尝试设置响应的contentType和header属性,但似乎没有设置headerType中的contentType(浏览器试图下载文件而不是渲染它)。

res.contentType = 'text/html'; res.header('Content-Type','text/html'); return res.send('<html><body>hello</body></html>'); 

在不改变整个服务器的格式化程序的情况下,快速操作标题的方法:

restify响应对象也具有节点ServerResponse的所有“原始”方法。

 var body = '<html><body>hello</body></html>'; res.writeHead(200, { 'Content-Length': Buffer.byteLength(body), 'Content-Type': 'text/html' }); res.write(body); res.end(); 

如果您在restifyconfiguration中覆盖了格式化程序,则必须确保您具有text / html的格式化程序。 所以,这是一个configuration示例,它将根据响应对象(res)上指定的contentType发送json和jsonp-style或html:

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

另一个select是打电话

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

代替

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

自从答案发布以来,@dlawrence在他的回答中所描述的行为似乎已经发生了变化。 现在它的工作方式(至less在Restify 4.x中)是:

 const app = restify.createServer( { formatters: { 'text/html': function (req, res, body, cb) { cb(null, body) } } })