6

I'm using express.js's res.render function and I met some issue to set custom headers, I'm tried 4 kind of method and all failed

here is my code

Method 1

app.get('/login', function(req, res, next) {
  res.writeHead(200, {'Content-Type':'text/plain; charset=utf-8'});
  next()
});

app.get('/login', function(req, res) {
  res.locals.text="hello";  
  res.render('index');
});

It has a error log with this code: Error: Can't set headers after they are sent.


Method 2 (example from here)

app.get('/login', function(req, res, next) {
  res.header(200, {'Content-Type':'text/plain; charset=utf-8'});
  next()
});

app.get('/login', function(req, res) {
  res.locals.text="hello";
  res.render('index');
});

the code comes with the error: TypeError: field.toLowerCase is not a function


Method 3

app.get('/login', function(req, res) {
  res.writeHead(200, {'Content-Type': 'application/xhtml+xml; charset=utf-8'});
  res.locals.text="hello";
  res.render('index');
});

the code also has error: Error: Can't set headers after they are sent.


That's all the ways I can thought and find but still can't resolve, is there any ways to set custom header (especially encoding type) with res.render?

Andrew.Wolphoe
  • 420
  • 5
  • 18

2 Answers2

8

To set custom response header with res.render, you can use res.set(). Here is an example code:

app.get('/login', function(req, res) {
  res.set({'Content-Type': 'application/xhtml+xml; charset=utf-8'});
  res.locals.text="hello";
  res.render('index');
});

Please check Express document for more details about res.set()

shaochuancs
  • 15,342
  • 3
  • 54
  • 62
0

If you want to set an header for your response, you can use setHeader method on http.ServerResponse object.

var server = require('http').createServer(function(req, res) {      
    res.setHeader('content-type', 'application/json');      
    res.write(headerStr);
    res.end();
});
Navoneel Talukdar
  • 4,393
  • 5
  • 21
  • 42