【问题标题】:Node.js - Content-Type for html file which has javascript file too?Node.js - html 文件的内容类型也有 javascript 文件?
【发布时间】:2021-07-26 10:16:51
【问题描述】:

响应对象的 writeHead 方法中的 Content-Type 应该是什么?

文本/纯文本或应用程序/javascript?

index.html 也有 index.js,Node.js http 服务器会将这两个文件发送到客户端(.html 和 .js)。

我在 chrome 中遇到以下错误

资源解释为脚本,但使用 MIME 类型 text/html 传输:"http://localhost:8111/index.js"

Node.js

var httpServer = http.createServer(function(request,response){
                fs.readFile(__dirname + '/index.html', function(error,data){
                                response.writeHead(200);
                                response.end(data);
                });
                });

httpServer.listen(8111);

index.html 有:

<script src="index.js"></script>

【问题讨论】:

  • 你在哪里提供 js 文件?您发送 html 文件以响应所有请求?
  • 我需要和另一个response.send()分开发送吗?
  • 您必须单独发送它以响应不同的请求。这意味着您必须查看请求是什么。
  • 你的服务器总是返回 index.html 内容,默认为 MIME text/html,也许你应该考虑使用 connect 或 expressjs 框架,这取决于你的需要。例如:stackoverflow.com/a/16333915/661140
  • 要完成@RobertoSánchez 所说的,使用express 提供目录文件就像​​app.use('/', express.static(__dirname)); 一样简单。

标签: node.js http


【解决方案1】:

包括指定index.html 文件内容类型的对象,如下所示。

response.writeHead(200); 

变成

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-07-31
    • 1970-01-01
    • 2023-03-10
    • 2021-03-19
    • 2015-10-15
    • 2020-03-02
    • 2020-08-06
    • 2020-02-24
    相关资源
    最近更新 更多