在Nodejs
中创建一个简单的Web服务器时,我遇到了一个奇怪的问题。 http服务器可以正常运行,并且可以接受请求和响应。但是,由于某种原因,它总是想要为所有内容发送content-type:
的text/plain
。例如,.js
和.css
文件始终以text/plain
的形式出现,而通常应以text/css
或application/javascript
的形式发送。我用来测试此功能的浏览器Chrome总是提示资源的MIME类型:Resource interpreted as Stylesheet but transferred with MIME type text/plain: "http://localhost:3000/test.css".
Resource interpreted as Script but transferred with MIME type text/plain: "http://localhost:3000/test-client.js".
这最终意味着css
从未应用于页面。我添加了一些日志记录,看来http响应正在向下发送正确的MIME类型。
我已经创建了我正在做的准系统版本。希望有人可以指出我编码的缺陷:
test.js
var http = require('http'),
fs = require('fs'),
url = require('url'),
path = require('path');
var contentTypes = {
'.html': 'text/html',
'.css': "text/css",
'.js': 'application/javascript'
};
http.createServer(function(request, response) {
// get file based on pathname
var uri = url.parse(request.url).pathname,
filename = path.join(__dirname, uri);
fs.exists(filename, function(exists) {
// if root directory, append test.html
if (fs.statSync(filename).isDirectory()) {
filename += 'test.html';
}
// figure out MIME type by file ext
var contentType = contentTypes[path.extname(filename)];
fs.readFile(filename, function(err, file) {
// errors?
if (err) {
response.writeHead(404, {'Content-type:': 'text/plain'});
response.write(err + "\n");
response.end();
} else {
console.log('MIME TYPE for: ', filename , contentType);
response.setHeader('Content-Type:', contentType);
response.writeHead(200);
response.write(file);
response.end();
}
});
});
}).listen(3000, function(){
console.log("server started and listening on port 3000");
});
test.html
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="test.css" type="text/css" />
</head>
<body>
<h1>Test</h1>
<div id="test"></div>
<script type="text/javascript" src="test-client.js"></script>
</body>
</html>
test.css
h1 {
color: red;
}
test-client.js
var div = document.getElementById('test');
div.innerHTML = 'test client ran successfully';
最佳答案
我认为问题在于,设置 header 时,您在:
之后使用了不必要的Content-Type
。您应该执行response.setHeader('Content-Type',contentType);
,或者执行以下操作(我认为更好):response.writeHead(200,{'Content-Type':contentType});