【发布时间】: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));一样简单。