mahemoff mahemoff - 1 year ago 159
Node.js Question

Express: Setting content-type based on path/file?

I know Express has the res.contentType() method, but how to set automatically content type based on path/file (including static content)?

Answer Source

Connect will automatically set the content type, unless you explicitly set it yourself. Here's the snippet that does it. It uses mime.lookup and mime.charsets.lookup

// mime type
type = mime.lookup(path);


// header fields
if (!res.getHeader('content-type')) {
  var charset = mime.charsets.lookup(type);
  res.setHeader('Content-Type', type + (charset ? '; charset=' + charset : ''));

If this isn't working for you, post your code as your custom code is likely interfering with the default behavior somehow.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download