Is it necessary to set a Content-Type in Node.js?

好久不见. 提交于 2020-11-29 08:40:51

问题


Just started playing with Node.js and after seeing a few examples I see that usually the Content-Type is set before returning some content.

Usually something like this for HTML:

res.writeHead(200, {'Content-Type': 'text/html'});
res.write(html);
res.end();

For image:

res.writeHead(200, {'Content-Type': 'image/png'});
res.write(img, 'binary');
res.end();

I read the docs for .write() and it says if no header is specified "it will switch to implicit header mode and flush the implicit headers"

With some testing I found I can just write one line like so:

res.end(html); // or
res.end(img);

These both work fine. I also tested with my local Apache server and when I viewed the headers being set when loading an image there was no Content-Type header set there.

Do I need to bother setting them? What situations or bugs might arise if I don't?


回答1:


The Content-Type header is technically optional, but then you are leaving it up to the browser to essentially guess what type of content you are returning. Generally you should always specify a Content-Type if you know the type (which you probably do).




回答2:


If you're using Express within your node app, then response.send(v) will implicitly pick a default content-type depending on the runtime type of v. More specifically, the behavior of express.Response.send(v) is as follows:

  • If v is a string (and no content-type has already been set) then send Content-Type: text/html
  • If v is a Buffer (and no content-type has already been set) then send Content-Type: application/content-stream
  • If v is any other bool/number/object (and no content-type has already been set) then send Content-Type: application/json

Here's the relevant source code from Express: https://github.com/expressjs/express/blob/e1b45ebd050b6f06aa38cda5aaf0c21708b0c71e/lib/response.js#L141




回答3:


Implicit headers mode means using res.setHeader() rather than node figuring out the Content-Type header for you. Using res.end(html) or res.end(img) does not serve back any Content-Type, I checked with an online http analyser. Rather they work because your browser figures it out.




回答4:


Of course not, if you are playing with NodeJs. But to make a maintainable code with different modules, large and API pages you should have 'Content-Type' in your server definition.

const http = require('http');

const host_name = 'localhost';
const port_number = '3000';

const server = http.createServer((erq, res) => {
    res.statusCode = 200;
    // res.setHeader('Content-Type', 'text/html');
    res.end("<h1> Head Line </h1> <br> Line 2 <br> Line 3");
});

server.listen(port_number, host_name, ()=> {
    console.log(`Listening to http://${host_name}:${port_number}`);
});


来源:https://stackoverflow.com/questions/22340066/is-it-necessary-to-set-a-content-type-in-node-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!