简体   繁体   中英

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.

But it does not include the corresponding Content-Type: text/html header automatically.

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.

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. 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? What version of express and how are you viewing the headers? I'm on Express 3.4.1 and 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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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