20

我想在 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>');
4

4 回答 4

28

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

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();
于 2013-03-30T20:04:51.260 回答
12

如果您在 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;
        }
    }
});
于 2012-06-21T00:08:05.270 回答
12

另一种选择是致电

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

代替

res.send('<html><body>hello</body></html>');
于 2015-06-14T18:27:36.290 回答
3

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)
    }
  }
})
于 2017-01-26T16:31:27.200 回答