你如何用restify发送html

Posted

技术标签:

【中文标题】你如何用restify发送html【英文标题】:how do you send html with restify 【发布时间】:2012-06-13 23:12:31 【问题描述】:

我想为我在 restify 中的一条路由发送纯 html 而不是 json 响应。我尝试设置响应的 contentType 和 header 属性,但它似乎没有在 header 中设置 contentType(浏览器尝试下载文件而不是渲染它)。

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

【问题讨论】:

【参考方案1】:

无需更改整个服务器的格式化程序即可快速操作标头:

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

【讨论】:

这不需要以调用next() 结束吗? 如果使用 gzip 编码,这将不起作用。最好使用自定义响应格式化程序并使用 res.send 以便计算正确的内容长度。 不错。谢谢,我正在使用 Restify(基于 Expressjs)替代方案,它可以工作。【参考方案2】:

如果您在 restify 配置中覆盖了格式化程序,则必须确保您有一个用于 text/html 的格式化程序。因此,这是一个配置示例,它将根据响应对象 (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;
        
    
);

【讨论】:

FWMI。您可以使用 restify 的库重新分配原始格式化程序。将第 3 行替换为:'application/json': require('restify/lib/formatters/json')【参考方案3】:

另一种选择是调用

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

代替

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

【讨论】:

【参考方案4】:

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

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

【讨论】:

以上是关于你如何用restify发送html的主要内容,如果未能解决你的问题,请参考以下文章

你如何用 Javascript 编写一个类? [复制]

你如何用javascript设置strftime?

你如何用 asynctask json 做 pojo

你如何用 jQuery 检测你何时接近屏幕底部? [复制]

打字稿:你如何用布尔或回调函数定义联合类型?

你如何用 Mingw 编译 python 3.5 代码?