你如何发送html与restify

Mon*_*key 20 http-headers node.js restify

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

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

ser*_*erg 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();
Run Code Online (Sandbox Code Playgroud)

  • 这不需要以对`next()`的调用结束吗? (2认同)

小智 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;
        }
    }
});
Run Code Online (Sandbox Code Playgroud)


Era*_*nah 11

另一种选择是打电话

res.end('<html><body>hello</body></html>');
Run Code Online (Sandbox Code Playgroud)

代替

res.send('<html><body>hello</body></html>');
Run Code Online (Sandbox Code Playgroud)