简体   繁体   English

使用res.render时,如何让Express自动设置Content-Type?

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

On Node.js, while using Jade as the template renderer, the only possible output of the res.render call is HTML. 在Node.js上,将Jade用作模板渲染器时,res.render调用的唯一可能输出是HTML。

But it does not include the corresponding Content-Type: text/html header automatically. 但是它不自动包含相应的Content-Type: text/html标头。

Is this by design? 这是设计使然吗? And if so, is there an easy way of implementing this without adding this header to all routes? 如果是这样,是否有一种简单的方法可以实现而无需在所有路由中添加此标头呢?

That depends on how you use jade. 这取决于您如何使用玉器。 jade only does the rendering for you, it does not know the appropriate header for the rendered content. jade仅为您执行渲染,它不知道渲染内容的适当标头。

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

You should choose whatever header is most suitable for you. 您应该选择最适合您的标题。

I wrote a demo app to force Content-Type: text/html for all get requests. 我编写了一个演示应用程序,对所有get请求强制使用Content-Type: text/html Then I tried disabling the function that sets that header, and that header still appears in my responses - so it does indeed seem to be set by default for me. 然后,我尝试禁用设置该标头的功能,并且该标头仍出现在我的响应中-因此,对于我来说,确实确实是默认设置了。

Are you sure that Content-Type is not set? 您确定未设置Content-Type吗? What version of express and how are you viewing the headers? 什么版本的快递以及如何查看标题? I'm on Express 3.4.1 and Chromium 我使用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

you can override res.render method 您可以覆盖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();
});

Do this just after creating your app. 在创建您的应用程序之后执行此操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM