2012-06-11 23 views
14

我想發送純html而不是json響應爲我的路線之一restify。我嘗試設置響應的contentType和header屬性,但它似乎沒有在頭中設置contentType(瀏覽器試圖下載文件而不是渲染它)。你如何發送HTML與restify

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

回答

21

快速的方式來操縱頭而不改變格式化爲全服務器:

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

這不需要以'next()'調用結束嗎? – Justin

+0

如果使用gzip編碼,這將不起作用。最好使用自定義響應格式化程序並使用res.send,以便計算正確的內容長度。 –

11

如果你已經覆蓋在的RESTify配置格式化程序,你必須確保你有text/html類型格式化。所以,這是將發送響應對象上指定JSON和JSONP式或HTML取決於contentType的結構的(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; 
     } 
    } 
}); 
+0

FWMI。您可以使用restify的庫重新分配原始格式化程序。將第3行替換爲:''application/json':require('restify/lib/formatters/json')' –

10

另一種方法是調用

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

而不是

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

好像行爲@dlawrence描述了當的答案被張貼因爲他的答案已經改變。現在它的工作方式(至少在Restify 4.x中)是:

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