Is a MIME header declaration good practice?

I've recently been working on a little project to serve static files. I want to be able to serve different types of files like:

html, jpg, png, pdf, doc...

All files seem to render correctly in different browsers without assigning a MIME type.

For example, if I serve an image and declare a MIME type I would write this in my node.js code:

response.writeHead(200, {'Content-Type': 'image/jpg'});
response.end(data);

Ignoring the MIME type will render the exact same results in different browsers:

response.writeHead(200);
response.end(data);

It is my understanding that if no MIME type is declared in the header, the browser will do its best to figure it out.

According to the HTTP specifications, the 'Content-Type' header is not required.

As with all multipart MIME types, each part has an optional "Content-Type", which defaults to text/plain.

Should I declare a MIME type for each response? Why?


You are quoting a MIME RFC. But in this context, Content-Type is under authority of RFC 7231, section 3.1.1.5 which reads (emphasis mine):

A sender that generates a message containing a payload body SHOULD generate a Content-Type header field in that message unless the intended media type of the enclosed representation is unknown to the sender.

On a practical note, if you omit this header you are leaving the client with guesswork over filename extensions and magic bytes. A Content-Type header will have precedence over those and save the client quite some work.

The relevant part of the RFC addresses this as follows:

Clients that do so risk drawing incorrect conclusions, which might expose additional security risks (eg, "privilege escalation"). Furthermore, it is impossible to determine the sender's intent by examining the data format: many data formats match multiple media types that differ only in processing semantics.


You must set the mime type. It is useful for the client to determine the type of data it is dealing with. Nothing to do with node. It is http spec.

链接地址: http://www.djcxy.com/p/46856.html

上一篇: asp.net下载IE6中的excel文件

下一篇: 是一个MIME头声明良好的做法?