Advertisement
kai-rocket

Zaffere MIME Type Explanation

May 1st, 2021
298
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None
  1.  
  2. Zaffere 2021-05-01
  3.  
  4. we have to understand how createServer works and how and what tells our browsers to render files in which formats.
  5. I think most softwares know how to render stuff in the right format based on the file extension (eg. .jpg, .png etc..)
  6. When it comes to the browsers, it uses the MIME type to decide at which format to render the file. if MIME type is not set correctly, then browsers would misinterpret
  7. The createrServer method takes in a function with the request and response object as params and we have access to the req and res properties with them to handle incoming and outgoing request/response.
  8. So that function runs ONCE EACH TIME a request is made to the server. And each time a req comes in we have to send back a response.
  9.  
  10. So now in the response object, we have access to the HTTP header property and this allows us to set HTTP headers in the response. (HTTP Headers are how client and servers pass additional information with key:value pairs like the ‘Content-type’, ’Response status’ and etc. we can find a list of them with google search)
  11.  
  12. So the reason why our css files are being loaded in but not read correctly is Not because the file is not in our working directory but because of the MIME type. The HTML file we loaded with Content-type: text/html (maybe not explicitly by you but in the meta data in the HTML file itself) has additional files to depend on (like the css files, and those files has different Content-types) and those files have to be fetched by the browsers all over again hence the multiple console.logs you saw in your script because the client(your browser) is making more requests to the server to fetch those files.
  13. Then if you notice you didn’t set a response header in your response from createServer (but I think the browser knows the file type because of the meta data in the html file itself so it renders correctly. In the case of the css file though, we never set a MIME type with its response so server just sends the file back without a MIME type and doing so confuses the browser and it doesn’t know what to do with that css file (or don’t know how to read the file).
  14.  
  15. So to fix this I made sure I checked the file extension of each of the requested file and then setting the correct Content-type in the response Headers (res.writeHead()) to tell the client(browser) ‘the language to speak in to the file’ (in this case css file only speaks css language) when that css file arrives.
Advertisement
RAW Paste Data Copied
Advertisement