簡體   English   中英

使用res.render時,如何讓Express自動設置Content-Type?

[英]How to have Express automatically set the Content-Type when using res.render?

在Node.js上,將Jade用作模板渲染器時,res.render調用的唯一可能輸出是HTML。

但是它不自動包含相應的Content-Type: text/html標頭。

這是設計使然嗎? 如果是這樣,是否有一種簡單的方法可以實現而無需在所有路由中添加此標頭呢?

這取決於您如何使用玉器。 jade僅為您執行渲染,它不知道渲染內容的適當標頭。

res.setHeader('Content-Type', 'text/html'); //or text/plain
res.render('yourtemplate');

您應該選擇最適合您的標題。

我編寫了一個演示應用程序,對所有get請求強制使用Content-Type: text/html 然后,我嘗試禁用設置該標頭的功能,並且該標頭仍出現在我的響應中-因此,對於我來說,確實確實是默認設置了。

您確定未設置Content-Type嗎? 什么版本的快遞以及如何查看標題? 我使用Express 3.4.1和Chromium

// app.js
var express = require('express');
var app = express();

function setHTML(req, res, next){
  res.header('Content-Type', 'text/html');
  next();
};

app.set('views', __dirname);
app.set('view engine', 'jade');
app.use(app.router);

//app.get('*', setHTML);
app.get('/', function(req, res){
  res.render('template');
});

require('http')
.createServer(app)
.listen(3000, function(){
  console.log('Listening on 3000');  
})

// template.jade
!!!
html
  body
    h1 hello thar

//response headers
HTTP/1.1 200 OK
X-Powered-By: Express
Content-Type: text/html; charset=utf-8
Content-Length: 60
Date: Thu, 17 Oct 2013 03:50:46 GMT
Connection: keep-alive

您可以覆蓋res.render方法

app.use(function(req, res, next){

    var oldRender = res.render;
    res.render = function(){
        res.header('Content-Type', 'text/html');
        oldRender.apply(this, arguments);
    };

    next();
});

在創建您的應用程序之后執行此操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM