在node.js中创建简单的html、css应用程序时遇到以下错误: 错误资源解释为样式表但使用 MIME 类型 text/html 传输:
server.js 代码是:
var http = require('http');
var fs = require('fs');
var url = require('url');
// Create a server
http.createServer( function (request, response) {
// Parse the request containing file name
var pathname = url.parse(request.url).pathname;
// Print the name of the file for which request is made.
console.log("Request for " + pathname + " received.");
// Read the requested file content from file system
fs.readFile(pathname.substr(1), function (err, data) {
if (err) {
console.log(err);
// HTTP Status: 404 : NOT FOUND
// Content Type: text/plain
response.writeHead(404, {'Content-Type': 'text/html'});
} else {
//Page found
// HTTP Status: 200 : OK
// Content Type: text/plain
response.writeHead(200, {'Content-Type': 'text/html'});
// Write the content of the file to response body
response.write(data.toString());
}
// Send the response body
response.end();
});
}).listen(9999);
// Console will print the message
console.log('Server running at http://127.0.0.1:9999/');
index.html
<link rel="stylesheet" type="text/css" href="css/style.css">
最佳答案
您可以使用 path
模块来识别扩展名并相应地设置 mime
类型:
// require path module
var path = require('path');
// check for extenstion
var pathname = url.parse(request.url).pathname;
var ext = path.extname(pathname).substr(1);
// check extension and set mime type
// HTTP Status: 200 : OK
if (ext === 'css') {
// check for css
response.writeHead(200, {'Content-Type': 'text/css'});
} else {
// Content Type: text/plain
// maybe also check .html type
response.writeHead(200, {'Content-Type': 'text/html'});
}
// Write the content of the file to response body
response.write(data.toString());
关于node.js - 错误资源解释为样式表但使用 MIME 类型 text/html : in nojd. js simple app 进行传输,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55923726/