0

From Node.js In Action:

To serve static files, you’ll use Node’s built-in http module. But when serving files via HTTP , it’s usually not enough to just send the contents of a file; you also should include the type of file being sent. This is done by setting the Content-Type HTTP header with the proper MIME type for the file.

Why is it necessary to specify MIME type here? What will happen if we don't specify it? In which cases it can be and can't be omitted?

Aquarius_Girl
  • 21,790
  • 65
  • 230
  • 411

1 Answers1

4

Why is it necessary to specify MIME type here?

Because otherwise web-browsers and other software won't know if the arbitrary stream of bytes they receive from your server is meant to be HTML or plaintext, for example.

What will happen if we don't specify it?

Then you force client applications to guess what the content is supposed to be - and with any guesses (even educated-guesses based on content-sniffing and heuristics) there's a strong probability of something going wrong.

In which cases it can be and can't be omitted?

As far as you're concerned (I assume you're a web application developer) then it should never be omitted: you should always specify it.

Rule-of-thumb: Always specify an explicit (and correct) Content-Type for your HTTP responses. If you don't know what the correct type is then fallback to using application/octet-stream, which tells the client that you don't know what it is either - at least that's being honest - and honesty is something we as a society value.

More specifically: the HTTP/1.1 spec does state the Content-Type header is optional, but honestly, in the 25+ years since HTTP/1.1 we've learned we should always send it. The only time it's okay to omit it is when there is no content (e.g. HTTP 204 No Content or Content-Length: 0).

Community
  • 1
  • 1
Dai
  • 141,631
  • 28
  • 261
  • 374